Convert a cron job into a timer that reports failure

applied · 40 min · Objective 2.5

Task

Take a backup job running under cron, convert it to a systemd timer, and gain the property cron does not give you: a failing run is visible without anyone having to read mail. Then prove the difference by making the job fail.

Steps

  1. Write a backup script that tars a directory to /backups and exits non-zero if the source is missing. Put it at /usr/local/bin/backup.sh.
  2. Install it as a cron entry running every minute. Let it run, then make it fail by removing the source directory. Observe that nothing anywhere reports the failure unless you go looking.
  3. Remove the cron entry. Write backup.service as a Type=oneshot unit invoking the same script.
  4. Write backup.timer with OnCalendar=*:0/1 for testing, and a [Install] section wanting timers.target.
  5. daemon-reload, then enable --now backup.timer. Confirm with systemctl list-timers that it is scheduled and shows the next run.
  6. Let it succeed once, then make it fail again. This time confirm that systemctl status backup.service reports the failure and the exit code, and that journalctl -u backup.service holds the output.
  7. Add Persistent=true and explain what it does for a machine that was switched off when the timer should have fired.

Verify

systemctl list-timers --all | grep backup
systemctl is-enabled backup.timer
# after making it fail:
systemctl status backup.service --no-pager | grep -qi 'failed' && echo "failure visible"
journalctl -u backup.service -n 5 --no-pager | tail -3
systemctl show backup.service -p ExecMainStatus --value    # non-zero

The contrast with step 2 is the whole lab: under cron the failure was silent unless somebody read mail that nobody reads. Under the timer, the unit is in a failed state, systemctl --failed lists it, and monitoring can see it.

Notes

Persistent=true is the systemd equivalent of anacron: if the machine was off when the timer should have fired, it runs once at the next boot. Cron simply misses the slot, which is why a laptop's overnight jobs never run.