Linux 入门实践:用 systemd 定时任务替代 crontab
在 Linux 服务器上,crontab 是最常见的定时工具,但它有一个短板:任务错过执行时间就不会补跑,日志也分散在系统日志里。systemd timer 正好补上这两点:它和 service 单元配合,支持开机补跑、精确到秒、按日历或间隔触发,还能用 systemctl 和 journalctl 统一查看状态。
下面用一个真实可用的例子:每天凌晨 2 点 30 分,把家目录下的 notes 笔记备份到 backup 目录。
先写 service 单元 /etc/systemd/system/notes-backup.service:
[Unit]
Description=备份 notes 目录
[Service]
Type=oneshot
ExecStart=/usr/bin/rsync -a --delete /home/username/notes/ /home/username/backup/notes/
注意 ExecStart 必须写绝对路径,Type=oneshot 表示执行一次就退出。把 username 换成自己的用户名,第一次执行前先手动确认目标目录存在。
再写 timer 单元 /etc/systemd/system/notes-backup.timer:
[Unit]
Description=每天凌晨备份 notes
[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true
[Install]
WantedBy=timers.target
Persistent=true 是关键:关机错过的时间点,开机后会补跑一次。OnCalendar 的写法很直观,星号分别对应年、月、日,后面是时分秒。
启用并检查:
sudo systemctl daemon-reload
sudo systemctl enable --now notes-backup.timer
systemctl list-timers --all | grep notes
systemctl status notes-backup.timer
想立刻验证,不用等到凌晨:
sudo systemctl start notes-backup.service
systemctl status notes-backup.service
常用排错命令:
journalctl -u notes-backup.service --since today
journalctl -u notes-backup.timer -n 50
systemd-analyze verify /etc/systemd/system/notes-backup.timer
systemd-analyze calendar "*-*-* 02:30:00"
最后一条命令会算出下一次触发时间,写错日历表达式时能马上发现。如果服务失败,先看 journalctl 里的退出码和 ExecStart 路径是否正确;如果 timer 没有触发,先查 list-timers 的 NEXT 列,再核对 Persistent 设置和系统时区 date 命令的输出。
和 crontab 对比,timer 的优势不在语法更短,而在状态可查、失败可追、错过可补。对需要可靠执行的备份、清理和健康检查任务,我现在会优先用 timer;只在临时、一次性的简单任务上继续用 crontab。先从一个每天备份的小任务开始,把 timer 跑通,再逐步替换其他定时任务,是最稳妥的迁移方式。
- 点赞
- 收藏
- 关注作者
评论(0)