用 systemd timer 替代 cron
服务器上原来有几条 cron 任务,最近统一换成了 systemd timer。主要图三点:日志直接进 journal,不用再自己重定向;用 systemctl list-timers 能一眼看到下次执行时间;关机期间错过的任务,开机后还能补跑。
先写 service
timer 本身不干活,它只负责按时启动同名的 service。先写要执行的任务:
# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
再写 timer
# /etc/systemd/system/backup.timer
[Unit]
Description=Run backup every night
[Timer]
OnCalendar=*-*-* 03:30:00
RandomizedDelaySec=10m
Persistent=true
[Install]
WantedBy=timers.target
Persistent=true 就是"错过了开机补跑";RandomizedDelaySec 让多台机器不要在同一秒一起跑。
时间表达式拿不准的话,可以先用 systemd-analyze calendar 检查一下下次触发时间:
$ systemd-analyze calendar "*-*-* 03:30:00"
启用
systemctl daemon-reload
systemctl enable --now backup.timer
systemctl list-timers
journalctl -u backup.service -n 50
注意 enable 的是 .timer 而不是 .service。想立即手动跑一次,直接 systemctl start backup.service 就行。