Replacing Cron with a systemd Service + Timer for Backups
Wrote a Bash backup script, packaged it as a systemd service unit, and scheduled it with a systemd timer — with status, logs and failure handling all visible through systemctl and journalctl.
Environment
- ›RHEL 9.4
- ›Bash, tar, systemd
- ›Target: nightly backup of /etc and /srv to /backup
Objectives
- 01Write an idempotent backup script with clear exit codes
- 02Run it as an unprivileged systemd service rather than a root cron job
- 03Schedule it with a systemd timer, including a randomised delay
- 04Make failures easy to spot via systemctl status and journald
Walkthrough
Step 1
Write the backup script
Created /usr/local/sbin/run-backup.sh — it tars /etc and /srv into a timestamped archive under /backup, prunes anything older than 14 days, and logs progress to stdout (captured by journald).
$ install -m 750 run-backup.sh /usr/local/sbin/run-backup.sh$ /usr/local/sbin/run-backup.sh --dry-run
Step 2
Create the service unit
Defined a oneshot service that runs the script as a dedicated 'backup' user, with Type=oneshot so systemd waits for it to finish before marking it done.
$ cat /etc/systemd/system/run-backup.service$ systemctl daemon-reload$ systemctl start run-backup.service$ systemctl status run-backup.service
Step 3
Add the timer unit
Created a matching .timer unit set to run daily at 02:00 with a 10-minute RandomizedDelaySec so multiple lab VMs don't all hit disk I/O at once. Enabled the timer, not the service, so it persists across reboots.
$ cat /etc/systemd/system/run-backup.timer$ systemctl enable --now run-backup.timer$ systemctl list-timers | grep run-backup
Step 4
Verify logs and failure handling
Forced a failure (read-only /backup mount) to confirm the service reports 'failed', the timer still fires the next day, and journalctl shows a clear error without digging through log files.
$ journalctl -u run-backup.service --since today --no-pager$ systemctl is-failed run-backup.service
Outcomes
- ✓One command (systemctl status) shows whether last night's backup succeeded — no log-grepping required
- ✓RandomizedDelaySec and Persistent=true behaviour now make sense in production cron replacements
- ✓Reusable unit-file template for future scheduled jobs