While traditional cron
jobs have been a staple in Linux automation for decades, systemd timers
offer a modern alternative with better reliability, logging, and dependency management. In this article, we’ll explore how to replace a typical cron job with a systemd timer unit and when it makes sense to use one over the other.
1. Why Use systemd Timers Instead of Cron?
- Built-in logging via
journalctl
- Dependency and startup awareness
- Flexible and precise scheduling
- Easier to manage with native systemd tools
2. Create a Service Unit
This is the unit that performs the task. Let’s say we want to run a backup script every day.
# /etc/systemd/system/backup.service
[Unit]
Description=Daily backup job
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
Make sure your script is executable:
chmod +x /usr/local/bin/backup.sh
3. Create a Timer Unit
This is the unit that schedules the above job.
# /etc/systemd/system/backup.timer
[Unit]
Description=Run backup daily at 2am
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
4. Enable and Start the Timer
sudo systemctl daemon-reexec
sudo systemctl enable --now backup.timer
You can now check the status of the timer and when it last/next ran:
systemctl list-timers
journalctl -u backup.service
5. Advanced Features
- RandomizedDelaySec for staggering execution across machines
- AccuracySec to control precision
- Timers can also be run based on boot time (
OnBootSec
) or after units become active
Conclusion
Systemd timers are powerful, especially for system administrators and devops engineers looking for more control and observability over scheduled tasks. They’re not only more robust than traditional cron jobs but are also integrated into the modern Linux ecosystem.
If you found this helpful, consider supporting me: buymeacoffee.com/hexshift