在 Debian(及大多数 Linux 发行版)里,“定时器”通常指 systemd timer。下面用最常见的方式说明如何设置周期。
systemd 定时器由两个文件组成:
.service:真正要执行的任务.timer:定义什么时候执行(周期)例如:/etc/systemd/system/mytask.service
[Unit]
Description=My Task
[Service]
Type=simple
ExecStart=/usr/local/bin/mytask.sh
例如:/etc/systemd/system/mytask.timer
[Unit]
Description=Run mytask every day
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
✅ 含义:每天凌晨 2 点执行
| 需求 | 写法 |
|---|---|
| 每分钟 | OnCalendar=*:0/1 |
| 每 5 分钟 | OnCalendar=*:0/5 |
| 每小时 | OnCalendar=hourly |
| 每天 3 点 | OnCalendar=*-*-* 03:00:00 |
| 每周一 4 点 | OnCalendar=Mon *-*-* 04:00:00 |
| 每月 1 号 | OnCalendar=*-*-01 00:00:00 |
| 每 30 秒 | OnCalendar=*:*:0/30 |
[Timer]
OnActiveSec=10min
OnUnitActiveSec=1h
OnActiveSec:timer 启动后多久执行OnUnitActiveSec:上次任务结束后多久再执行⚠️ 这个方式不保证固定时间点
systemctl daemon-reload
systemctl enable --now mytask.timer
查看状态:
systemctl list-timers
systemctl status mytask.timer
journalctl -u mytask.service
journalctl -u mytask.timer
Debian 也支持 cron:
crontab -e
示例(每天 2 点):
0 2 * * * /usr/local/bin/mytask.sh
如果你能告诉我:
我可以直接帮你写完整配置。