在 Debian(以及大多数 Linux 发行版)中,“定时任务”通常有两种主流方式:
下面分别说明。
crontab -e
* * * * * command
│ │ │ │ │
│ │ │ │ └─ 星期 (0-7,0和7都是周日)
│ │ │ └─── 月份 (1-12)
│ │ └───── 日期 (1-31)
│ └─────── 小时 (0-23)
└───────── 分钟 (0-59)
# 每天凌晨 3 点执行
0 3 * * * /home/user/backup.sh
# 每 5 分钟执行一次
*/5 * * * * /usr/bin/python3 /home/user/task.py
# 每周一 9:30
30 9 * * 1 /home/user/weekly.sh
crontab -l # 查看
crontab -r # 删除全部
系统级任务可放在:
/etc/crontab或/etc/cron.d/
适合系统服务、精确控制、日志记录。
sudo vim /etc/systemd/system/mytask.service
内容:
[Unit]
Description=My Task
[Service]
Type=oneshot
ExecStart=/home/user/mytask.sh
sudo vim /etc/systemd/system/mytask.timer
内容:
[Unit]
Description=Run My Task Daily
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now mytask.timer
systemctl list-timers
| 场景 | 推荐 |
|---|---|
| 简单脚本、个人任务 | crontab |
| 系统服务、需要日志 | systemd timer |
| 需要秒级控制 | systemd timer |
* * * * * /script.sh >> /var/log/script.log 2>&1
systemctl status cron
如果你愿意,可以告诉我:
我可以直接帮你写配置。