在 Debian(以及大多数现代 Linux 发行版)中,“定时器”通常指 systemd timer(推荐方式),当然也可以用传统的 cron。下面分别说明。
例如:每天执行一个脚本 /usr/local/bin/backup.sh
# /etc/systemd/system/backup.service
[Unit]
Description=Backup Service
[Service]
Type=simple
ExecStart=/usr/local/bin/backup.sh
# /etc/systemd/system/backup.timer
[Unit]
Description=Run backup daily
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable --now backup.timer
systemctl list-timers
systemctl status backup.timer
OnCalendar=*-*-* *:*:00
OnCalendar=hourly
OnCalendar=*-*-* 03:30:00
OnCalendar=Mon *-*-* 05:00:00
crontab -e
0 2 * * * /usr/local/bin/backup.sh
crontab -l
/etc/crontab
/etc/cron.d/
/etc/cron.daily/
/etc/cron.hourly/
| 对比项 | systemd timer | cron |
|---|---|---|
| 精度 | 高 | 一般 |
| 日志 | journalctl | 邮件/日志 |
| 依赖控制 | 强 | 弱 |
| 使用难度 | 稍复杂 | 简单 |
✅ 服务器/系统服务:推荐 systemd timer
✅ 简单脚本/个人任务:cron 更方便
如果你有具体需求(比如“每 5 分钟执行一次”“开机 10 分钟后执行”),可以告诉我,我可以直接帮你写配置。