Sub topic 8
Preventing Overlapping Runs with `flock`
Assume you are comfortable with shell scripts, process exit codes, file permissions, and basic cron syntax. This chapter explains how to stop a recurring job from starting while an earlier run is still active.
Why overlapping runs are dangerous
A scheduler starts jobs according to time. It does not automatically know whether the previous run finished.
For example, a backup scheduled every 15 minutes may take 20 minutes on a busy server. The second run then starts before the first one finishes. Two processes may:
- Read or write the same files at the same time.
- Upload duplicate data.
- Consume twice the expected CPU, memory, or database connections.
- Produce conflicting results.
- Make a slow system even slower.
A lock is a coordination mechanism that allows only one process to enter a critical section, which is the part of a job that must not run concurrently.
How `flock` works
flock uses an operating system file lock. The lock is associated with an open file descriptor or lock file. When the process exits, the operating system releases the lock, including after many abnormal terminations.
The lock file itself does not need to be deleted. Its presence does not mean that a job is running. The kernel lock state matters.
Use -n for a non-blocking lock. If another process owns the lock, flock exits immediately with a nonzero status.
# root's crontab
[email protected]
PATH=/usr/local/bin:/usr/bin:/bin
# Skip this run if the previous run is still active
*/15 * * * * /usr/bin/flock -n /run/lock/sync.lock /usr/local/bin/sync.sh >> /var/log/sync.log 2>&1The scheduler starts flock, which tries to lock /run/lock/sync.lock. On success, flock runs sync.sh and returns the script's exit status. On failure to acquire the lock, it exits without starting the script.
The account running the job must be able to create or open the lock file. Create the directory with suitable ownership and permissions if necessary.
Waiting instead of skipping
Non-blocking mode is usually appropriate for frequent jobs. A missed run can wait for the next scheduled activation.
Use -w when the current run should wait for a limited period:
/usr/bin/flock -w 300 /run/lock/report.lock /usr/local/bin/report.shThis waits for up to 300 seconds. If the lock remains unavailable, flock exits with failure. Avoid waiting forever. A stuck process could cause every later scheduler invocation to accumulate.
Locking inside a script
Locking inside the script protects the job even when it is started manually or by more than one scheduler.
#!/usr/bin/env bash
set -euo pipefail
exec 9>/run/lock/sync.lock
if ! flock -n 9; then
printf '%s\n' "sync already running" >&2
exit 75
fi
printf '%s\n' "starting sync"
# Commands that must not overlap go here.File descriptor 9 refers to the opened lock file. The lock remains held while the script runs and is released when the script exits. Exit code 75 distinguishes “skipped because busy” from an actual job failure. Configure monitoring to treat that result deliberately. A skipped run may be normal, or it may indicate that the job is consistently taking too long.
Choosing lock behavior
| Situation | Lock behavior |
|---|---|
| Frequent poller where the next run is sufficient | `flock -n` and skip |
| Important task that may start slightly late | `flock -w` with a bounded wait |
| Job can be safely queued | Use a queue or worker system instead of a simple lock |
A lock prevents simultaneous execution. It does not make a job safe to repeat after a partial failure. The job should also use idempotent operations, meaning repeating a completed step produces the intended result rather than duplicate or corrupted data.
Exercise
A cron job runs every ten minutes, but a normal run takes twelve minutes. Which flock mode prevents two copies while allowing the next scheduled activation to try again later?
Show answer
Use flock -n with a shared lock path. The overlapping activation exits immediately, and the following activation tries again.