Sub topic 8
Preventing Overlapping Runs with flock
This chapter assumes you can write a crontab entry, read a systemd unit, and understand file descriptors and exit codes at a basic level. It builds on the previous chapters on cron syntax and systemd timers.
Why overlap happens
A scheduler starts a job at fixed times. It does not wait for the previous run to finish. If a job runs every 15 minutes and one run takes 20 minutes, cron starts a second copy while the first is still working.
Overlap usually has ordinary causes:
- A database or network share is slow, so a normally quick job takes longer than its interval.
- A job hangs on a dead connection and never finishes.
- You run the job by hand to test it while the scheduled run starts.
- The input grew over months and the job slowly outgrew its schedule.
Two copies of the same job can corrupt shared files, send duplicate emails, double-process a queue, or compete for CPU and I/O until both run even slower. The slowdown also makes the next overlap more likely, so the problem feeds itself.
What flock does
flock is a utility from util-linux. It takes an advisory lock on a file and then runs a command while holding that lock.
- Advisory means the kernel enforces the lock only among processes that ask for it. A process that ignores the lock can still open and write the file.
- The lock belongs to an open file description. When the process holding it exits, for any reason including
kill -9, the kernel releases the lock.
The second point is the main reason to use flock instead of a hand-made "PID file". A PID file left behind by a crash blocks every later run until someone deletes it. A flock lock cannot go stale, because the kernel drops it when the process dies.
The lock file is only a rendezvous point. Its contents do not matter, and it is normally empty.
The three behaviors when the lock is taken
When another process holds the lock, flock can do one of three things:
| Option | Behavior | Typical use |
|---|---|---|
| (none) | Block until the lock is free, then run | Rarely right for cron, because waiting jobs pile up |
| `-n` (`--nonblock`) | Give up immediately with exit status 1 | Skip a run if the previous one is still going |
| `-w SECONDS` (`--timeout`) | Wait up to that many seconds, then give up | Short jobs that may briefly collide |
The default blocking mode is dangerous in a scheduler. If a job hangs, every later run queues behind it and waits. When the hang clears, all the queued runs fire one after another. For most periodic jobs, -n is the right choice: skipping a run is better than stacking them.
You can change the exit code used for a failed lock with -E. This lets you tell "lock busy" apart from "the command failed", because both would otherwise return 1 in some cases:
flock -n -E 75 /run/lock/sync.lock /usr/local/bin/sync.sh
echo "exit status: $?"Here status 75 means the lock was busy. Any other value is the command's own exit status.
Wrapping a command in a crontab
The simplest pattern puts flock in front of the command:
# root's crontab
PATH=/usr/local/bin:/usr/bin:/bin
*/15 * * * * /usr/bin/flock -n /run/lock/sync.lock /usr/local/bin/sync.sh >> /var/log/sync.log 2>&1Cron runs flock, which tries the lock on /run/lock/sync.lock. If it gets the lock, it runs sync.sh and releases the lock when the script exits. If it does not, it exits at once and sync.sh never starts.
Some points to check:
- Use the full path to
flock, or setPATHas shown. Cron's environment is minimal. /run/lockis a good location on most distributions because it is a temporary filesystem cleared at boot. Check that the job's user can write there. For a job running as a normal user, use a directory they own, such as$HOME/.cache/or/run/user/UID/.- Each distinct job needs its own lock file. Sharing one file makes unrelated jobs block each other.
Locking inside the script
You can also take the lock from within the script, so it is protected no matter how it is started. This covers a person running the script by hand. It also covers a second scheduler entry that points at the same script.
#!/usr/bin/env bash
set -euo pipefail
lockfile=/run/lock/report.lock
# Open file descriptor 9 on the lock file, then try to lock it.
exec 9>"$lockfile"
if ! flock -n 9; then
echo "report.sh: previous run still active, skipping" >&2
exit 0
fi
# The lock is held from here until this script exits.
echo "starting report at $(date -Is)"
sleep 30 # replace with the real work
echo "finished report at $(date -Is)"exec 9>"$lockfile" opens the file on descriptor 9 for the life of the script. flock -n 9 locks that descriptor. The lock is released when the script ends and descriptor 9 closes.
The script exits with status 0 when it skips. That is a deliberate choice. A skipped run is a normal event, not a failure, and exiting non-zero would trigger failure alerts. The next chapters cover alerting, but it is worth deciding now which outcomes count as failures. If skipping repeatedly means something is wrong, for example a run hung for hours, a heartbeat check will catch it, because the job stops reporting success.
Seeing it work
You can test locking in a terminal with two shells.
In the first shell:
flock /tmp/demo.lock sleep 60In the second shell, while the first is still running:
flock -n /tmp/demo.lock echo "got the lock"
echo "exit status: $?"The second command prints only exit status: 1. It never prints got the lock. After the first shell's sleep ends, repeating the second command prints the message and status 0.
The following diagram shows how three scheduled starts behave when the first run is slow.
Gotchas
Child processes inherit the lock
A child process inherits the open file descriptor, and with it the lock. If your job starts a background process that outlives the job, that process keeps the lock after the parent exits. Every later run is then skipped until the background process ends.
The -o (--close) option closes the lock descriptor before running the command, so children do not inherit it. Note that it applies when flock runs a command, and the lock is then released when flock itself would drop it. Normally the better fix is to avoid leaving background processes behind.
Do not delete the lock file
Removing the lock file while a job holds it is a bug. A new run creates a new file with a new inode and locks that one. Now two runs hold "the lock" on different files. Leave lock files in place. They are empty and harmless.
The lock must be on a local filesystem
Advisory locks across network filesystems such as NFS are unreliable on some setups. They protect only processes that share the same kernel's view of the file. Keep lock files on local storage, such as /run/lock. Locks also cannot coordinate jobs on different machines. For that you need a different mechanism, such as a database row or a distributed lock service.
Pipelines and subshells
The lock lasts only as long as the process that owns the descriptor. In a script, do not open the lock inside a subshell or a command substitution $(...) and expect it to hold afterward. The subshell exits and releases the lock. Open it in the main script body as shown above.
systemd already guards its own units
For systemd timers, you often need no flock. A timer activates a service unit. If that service is still active when the timer fires again, systemd does not start a second copy. A Type=oneshot service stays in the "activating" state while its command runs, so a repeated activation is a no-op.
This protects only that one unit. It does not protect against someone running the script by hand, or against two different units that run the same script. When those cases matter, use flock inside the script as well. The two approaches combine without conflict.
Cron has no such protection, so any cron job that can run longer than its interval needs flock. That includes jobs with an unpredictable runtime.
Choosing the lock behavior
- Use
-nfor jobs that run on a frequent schedule and produce the same result no matter which run does the work. Skipping one run loses nothing. - Use
-wwith a short timeout when a brief overlap is expected and the work must happen, for example a job that must wait for a short-running maintenance task. - Avoid the default blocking mode in scheduled jobs. It converts one hang into a growing pile of waiting processes.
A lock prevents two copies from running together, but it does not make a single run safe to repeat or interrupt. That is the subject of the next chapter, on idempotent jobs and atomic writes.
Exercise
A cron job runs every 5 minutes with flock /run/lock/job.lock /usr/local/bin/job.sh (no -n). One run hangs forever. What happens over the next hour, and what single change fixes the pile-up?
Show answer
Each later run starts flock, finds the lock held by the hung process, and blocks waiting for it. About 12 flock processes accumulate in the hour. If the hang ever clears, they run one after another in a burst. Adding -n makes each new start exit immediately instead of waiting, so no processes accumulate. A timeout on the job itself (covered later) is still needed to end the hang.
Exercise
A script takes its lock with exec 9>/run/lock/x.lock; flock -n 9. It then launches long_task & and exits. Why might the next scheduled run be skipped even though the script has finished, and how do you confirm it?
Show answer
The background long_task inherited descriptor 9 and still holds the lock. You can confirm it by running lsof /run/lock/x.lock or fuser -v /run/lock/x.lock, which lists the process with the file open. Fix it by not leaving a background process behind, or by closing the descriptor for the child, for example long_task 9>&- &.