在 Debian(以及其它使用 systemd 的 Linux 发行版)中,定时任务通常通过 systemd timer + service 单元文件 来实现,相当于“加强版 crontab”。
下面一步步说明如何写单元文件。
一个 systemd 定时任务通常有两个文件:
.service 文件:定义“要执行什么”.timer 文件:定义“什么时候执行”路径(推荐):
/etc/systemd/system/mytask.service
内容:
[Unit]
Description=My scheduled task
[Service]
Type=oneshot
ExecStart=/usr/local/bin/mytask.sh
✅
Type=oneshot表示任务执行一次就结束
✅ExecStart必须是绝对路径
路径:
/etc/systemd/system/mytask.timer
内容:
[Unit]
Description=Run mytask daily
[Timer]
OnCalendar=*-*-* 00:00:00
Persistent=true
Unit=mytask.service
[Install]
WantedBy=timers.target
说明:
OnCalendar=*-*-* 00:00:00:每天 0 点Persistent=true:如果系统关机错过时间,开机后补执行Unit=:指定要运行的 service(默认同名可不写)| 需求 | 写法 |
|---|---|
| 每天 3 点 | *-*-* 03:00:00 |
| 每周一 9 点 | Mon *-*-* 09:00:00 |
| 每月 1 号 | *-*-01 00:00:00 |
| 每 10 分钟 | *:0/10:00 |
| 每小时 | hourly |
| 每天 | daily |
也支持:
OnBootSec=5min
OnUnitActiveSec=1h
sudo systemctl daemon-reload
sudo systemctl enable mytask.timer
sudo systemctl start mytask.timer
systemctl status mytask.timer
systemctl list-timers
journalctl -u mytask.service
✅ 可记录日志(journalctl)
✅ 支持依赖、失败重试
✅ 更精确的时间控制
✅ 系统级 / 用户级都支持
如果你有具体需求(比如“每 5 分钟”、“开机后延迟执行”、“用户级 timer”),可以告诉我,我可以直接帮你写完整文件。