在 Debian(以及其他使用 systemd 的现代 Linux 发行版)中,定时任务推荐用 systemd timer(取代传统的 cron)。下面按“周期配置”详细讲清楚。
一个定时任务通常由两个文件组成:
路径一般放在:
/etc/systemd/system/
/etc/systemd/system/mytask.service
[Unit]
Description=My scheduled task
[Service]
Type=oneshot
ExecStart=/usr/local/bin/myscript.sh
/etc/systemd/system/mytask.timer
[Unit]
Description=Run mytask daily
[Timer]
OnCalendar=*-*-* 00:00:00
Persistent=true
[Install]
WantedBy=timers.target
systemctl daemon-reexec
systemctl enable --now mytask.timer
查看状态:
systemctl list-timers
OnCalendar 是最常用的周期配置方式。
| 需求 | 配置 |
|---|---|
| 每分钟 | *-*-* *:*:00 |
| 每小时 | *-*-* *:00:00 |
| 每天 3 点 | *-*-* 03:00:00 |
| 每周一 9 点 | Mon *-*-* 09:00:00 |
| 每月 1 号 | *-*-01 00:00:00 |
| 每年 1 月 1 日 | *-01-01 00:00:00 |
✅ 支持星期缩写:Mon Tue Wed Thu Fri Sat Sun
[Timer]
OnUnitActiveSec=1h
含义:
常用单位:
secminhdayweek示例:
OnUnitActiveSec=30min
OnBootSec=5min
OnBootSec=10min
RandomizedDelaySec=300
Persistent=true
❌ 不写或 false:错过就错过
# 查看所有定时器
systemctl list-timers
# 查看某个 timer
systemctl status mytask.timer
# 手动触发
systemctl start mytask.service
# 查看日志
journalctl -u mytask.service
如果你只是想快速用:
crontab -e
示例(每天 2 点):
0 2 * * * /usr/local/bin/myscript.sh
⚠️ cron 不适合系统服务级任务,也不支持开机补执行。
✅ 推荐:
systemd timer✅ 简单脚本:
如果你愿意,可以告诉我:
我可以直接帮你写完整配置。