Making jobs reliable
Prevent overlapping runs, detect silent failures and keep jobs safe to repeat.
A job that runs once a day will one day fail, hang or run twice. Plan for it.
Avoid overlapping runs
If a run takes longer than the interval, the next one starts while the first is still working. Use a lock so only one copy runs.
*/5 * * * * /usr/bin/flock -n /tmp/sync.lock /usr/local/bin/sync.shflock -n exits at once if another run holds the lock.
Make jobs idempotent
Idempotent means running it twice has the same result as running it once. Prefer rsync over appending, write to a temporary file and rename it when done, and skip work that is already done.
Know when it fails
A job that fails silently is worse than no job. Use a dead man switch: the job pings a monitoring URL after a successful run, and the service alerts you when the ping does not arrive.
30 2 * * * /usr/local/bin/backup.sh && curl -fsS -m 10 https://monitor.example.com/ping/abc123The && runs the ping only if the backup exits with status 0.
Checklist
- Absolute paths and a clear environment.
- Output goes to a log with timestamps.
- A lock prevents overlaps.
- Safe to run twice.
- An alert if it does not finish.
- A restore test for backups. A backup that you never restored is a guess.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.