QT #2 - Cron jobs that don't pile up
A Quick Tip on cron jobs that overlap: when a run takes longer than the interval, copies start stacking up. flock, from util-linux, lets only one run at a time, with options to skip, wait or report.
Cron doesn't care whether the last run finished. A job set to run every five minutes starts every five minutes, and if one run takes seven because the network was slow or the backup was bigger than usual, the next one starts on top of it. Two copies fight over the same files, the load climbs, the next run is even slower, and copies start stacking up.
It's easy to see with a stand-in job that just sleeps for 20 seconds, started three times in a row:
$ for i in 1 2 3; do ./backup.sh & done $ pgrep -fc backup.sh 3
Source
$ for i in 1 2 3; do ./backup.sh & done
$ pgrep -fc backup.sh
3Three copies, all running.
One at a time with flock #
flock comes with util-linux, so it's already on nearly every Linux machine. It takes a lock on a file, runs the command, and lets go when the command ends. A second flock on the same file finds the lock taken and, with -n, gives up right away:
*/5 * * * * flock -n /run/lock/backup.lock /usr/local/bin/backup.shThat's the whole fix. Here it is with the options that matter, run for real:

-
-nskips the run if the lock is taken, with exit code 1. -
-w 5waits up to five seconds for the lock before giving up. Good for jobs that should run late rather than not at all. -
-E 75changes the exit code for "skipped", so a monitoring script can tell a skipped run from a real failure, which also returns 1 in many scripts.
Why a lock file beats a PID file #
The old way was a PID file: write the process number at the start, delete it at the end, and check for it before starting. Then the job crashes or gets killed, the file stays behind, and the job never runs again until someone deletes it by hand.
flock doesn't have that problem. The lock belongs to the open file, not to the file on disk, so the kernel drops it the moment the process ends, however it ends. The empty backup.lock left in /run/lock means nothing, and /run/lock is cleared on every boot anyway.
Inside a script #
When the lock belongs inside the script itself, so it's protected no matter who starts it, two lines at the top do it:
exec 9>/run/lock/backup.lock
flock -n 9 || exit 0The first line opens the lock file as file descriptor 9 for the rest of the script. The second takes the lock or quits quietly. The lock lasts until the script ends.
The same flock -n prefix works in a systemd service's ExecStart= line too.
One catch #
The lock is a gentleman's agreement. It only stops programs that also ask flock for the same file. Anything that ignores it, like the same job started by hand without flock, runs anyway.