用 systemd timer 替代 crontab

2026-05-17 · Linux

cron 的输出默认丢掉或者发邮件,出了问题很难查。systemd timer 的日志直接进 journal,还能设置随机延迟。

示例

# /etc/systemd/system/backup.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh

# /etc/systemd/system/backup.timer
[Timer]
OnCalendar=*-*-* 03:00:00
RandomizedDelaySec=15m
Persistent=true

[Install]
WantedBy=timers.target
systemctl enable --now backup.timer
systemctl list-timers
journalctl -u backup.service

Persistent=true 表示如果关机错过了执行时间,开机后会补跑一次。