Sub topic 2
Choosing between cron and systemd timers
This chapter assumes you can edit crontabs and unit files as root, write Bash scripts that use exit codes, and read logs with journalctl. Cron and systemd timers both start jobs on a schedule. Each one suits different jobs.
Comparing the two schedulers
| Feature | cron | systemd timer |
|---|---|---|
| Schedule format | Five time fields | `OnCalendar` expression |
| Missed runs | Skipped while the machine is off | Runs once after boot with `Persistent=true` |
| Output | You redirect it to a file | Goes to the journal |
| Setup | One crontab line | Two unit files |
Use cron for a simple job. Use a systemd timer when you need catch-up runs, journal logs, or resource limits.
Capturing output and logs
Cron discards output unless you redirect it:
*/15 * * * * /usr/local/bin/sync.sh >> /var/log/sync.log 2>&1A systemd service writes its output to the journal. Read it with journalctl -u sync.service --since today.
Exit status: making failures loud
A script reports success with exit status 0 and failure with any other value. Put set -euo pipefail at the top of each script so the first error stops the job. Otherwise the script can keep running and report success.
Preventing overlapping runs with flock
A job that runs longer than its interval can start a second copy. The flock command takes a lock file:
/usr/bin/flock -n /run/lock/sync.lock /usr/local/bin/sync.shThe -n flag makes a new run exit at once when the lock is already held. The kernel releases the lock when the process ends, even after a crash.
Idempotent jobs and atomic writes
An idempotent job gives the same result when it runs twice. Write the output to a temporary file in the same directory, then rename it. A rename on one filesystem is atomic, so readers never see a half-written file.
#!/usr/bin/env bash
set -euo pipefail
out=/var/backups/disk-report.txt
tmp=$(mktemp "${out}.XXXXXX")
trap 'rm -f "$tmp"' EXIT
df -h / > "$tmp"
mv "$tmp" "$out"Exercise
Exercise
A server is powered off at 02:30 and boots at 09:00. Which scheduler still runs the missed nightly backup, and which setting does that?
Show answer
A systemd timer with Persistent=true runs the missed job once after boot. Cron skips it.