用 Systemd Timer 替代 Cron:更现代的 Linux 定时任务方案

不少人还在用 crontab -e 管理定时任务,但 cron 有几个老毛病:服务器重启后错过的任务不会补跑、执行日志分散难查、任务失败没有任何感知。而 systemd 自带的 Timer 单元,正好把这些坑一个个填平。

为什么换 Systemd Timer

  • 错过补跑:加一行 Persistent=true,机器关机期间错过的触发会在下次启动时立即补执行。
  • 日志集中:所有输出直接进 journal,一条 journalctl -u myjob.service 就能回溯执行历史。
  • 依赖编排:可以声明在网络就绪、目录挂载之后才触发,这是 cron 做不到的。

三步完成迁移

第一步,写服务单元 /etc/systemd/system/backup.service:

[Unit]
Description=Nightly backup

[Service]
Type=oneshot
ExecStart=/opt/scripts/backup.sh

第二步,写计时器 /etc/systemd/system/backup.timer:

[Unit]
Description=Run backup daily

[Timer]
OnCalendar=*-*-* 03:30:00
Persistent=true

[Install]
WantedBy=timers.target

第三步,启用并确认:

systemctl daemon-reload
systemctl enable --now backup.timer
systemctl list-timers backup.timer

两个实用细节

OnCalendar 支持自然语言式写法,如 Mon..Fri 09:00 表示工作日触发;再配 RandomizedDelaySec=10m 给执行时间加随机抖动,避免集中任务同时打爆机器。最后接入 Uptime Kuma 的 Push 心跳监控,脚本末尾 curl 一次上报地址,任务超时未上报立刻告警——一套下来,定时任务的可靠性直接拉满。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容