在 Debian 里“定时器脚本”通常有两种常见理解,我先分别说明,你按需要选:
这是现代 Debian 官方推荐方式,比 cron 更强大。
例如:/etc/systemd/system/backup.service
[Unit]
Description=Backup Script
[Service]
Type=oneshot
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
✅ 优点:
适合简单任务。
/usr/local/bin/hello.sh
#!/bin/bash
echo "hello $(date)" >> /var/log/hello.log
chmod +x /usr/local/bin/hello.sh
crontab -e
示例(每天 2 点执行):
0 2 * * * /usr/local/bin/hello.sh
grep CRON /var/log/syslog
*-*-* 03:00:00*:0/10:00Mon *-*-* 05:00:00分 时 日 月 周
0 2 * * * # 每天2点
*/10 * * * * # 每10分钟
| 场景 | 推荐 |
|---|---|
| 系统级任务 | systemd timer |
| 简单脚本 | cron |
| 需要日志/失败重试 | systemd |
| 用户级任务 | cron 或 systemd --user |
如果你愿意,可以告诉我:
我可以直接帮你写完整可用的脚本。