温馨提示×

debian定时器怎么配置时间

小樊
37
2026-10-13 16:37:16
栏目: 智能运维

在 Debian 里“定时器”通常指 systemd timer(代替 crontab 的现代方式),也可能是 cron。下面分别说明。


一、systemd timer(推荐)

1. 基本组成

  • .service:真正要执行的任务
  • .timer:定义什么时候执行

2. 示例

/etc/systemd/system/backup.service

[Unit]
Description=Backup job

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh

/etc/systemd/system/backup.timer

[Unit]
Description=Run backup daily

[Timer]
OnCalendar=*-*-* 03:30:00
Persistent=true

[Install]
WantedBy=timers.target

3. 时间格式(OnCalendar)

YYYY-MM-DD HH:MM:SS

例子:

  • 每天 3:30
    OnCalendar=*-*-* 03:30:00
  • 每周一 9:00
    OnCalendar=Mon *-*-* 09:00:00
  • 每 10 分钟
    OnCalendar=*:0/10
  • 每小时
    OnCalendar=hourly

也支持:

OnBootSec=10min
OnUnitActiveSec=1h

4. 启用

systemctl daemon-reload
systemctl enable --now backup.timer

5. 查看状态

systemctl list-timers
systemctl status backup.timer

二、cron(传统方式)

1. 编辑定时任务

crontab -e

2. 时间格式

分 时 日 月 周 命令

示例:

  • 每天 3:30
    30 3 * * * /usr/local/bin/backup.sh
  • 每 10 分钟
    */10 * * * * command
  • 每周一 9 点
    0 9 * * 1 command

3. 查看

crontab -l

三、如何选择

  • 系统服务 / 服务器任务 → systemd timer
  • 简单脚本 / 用户任务 → cron

如果你愿意,可以告诉我:

  • 你想“多久执行一次”
  • 是系统级还是用户级
  • 用 cron 还是 systemd

我可以直接帮你写完整配置。

0 踩