Wrap the command in flock -n /path/to/lock command. When a previous run still holds the lock, flock exits immediately instead of starting a second copy, so a slow job never stacks on top of the next scheduled tick.
A cron entry that fires every five minutes assumes the job finishes in well under five minutes. The day it does not — a backup that hits a slow disk, a sync that waits on a busy database — cron happily launches a second copy on top of the first, then a third, until the host is thrashing on duplicated work. flock is the small, reliable fix: one lock file, and any run that would overlap is refused rather than queued.
What you’ll accomplish
- Guarantee that only one instance of a cron job runs at a time.
- Choose between failing fast (
-n), waiting a bounded time (-w), and blocking forever (the dangerous default). - Keep cron from emailing an alert every time a run is correctly skipped.
- Log skipped runs so an overlap is visible instead of silent.
- Understand why the lock releases on its own — even after a crash — with no stale-lock cleanup.
Prerequisites
- A Linux system running cron (Vixie cron or cronie — both parse the same crontab syntax).
- The
flock(1)command from util-linux. It ships on essentially every Linux distribution; confirm withflock --version. - Shell access to edit the relevant crontab (
crontab -e, or a file under/etc/cron.d/). - A lock file location the cron user can write to. Good choices are
/var/lock,/run/lock, or/tmp.
flock here is the Linux/util-linux tool built on the flock(2) system call. macOS and the BSDs ship a different flock (or none), so the flags below are Linux-specific.
How it works
flock takes an advisory lock on a file through the flock(2) system call, runs your command while holding it, and drops the lock when the command exits. The lock is advisory: it only blocks other processes that also try to flock the same file. It does nothing to processes that ignore locking and simply open the file — so the whole scheme works because every copy of the job goes through flock, not because the file itself is protected.
The important property is that the lock is tied to an open file descriptor, not to the existence of the file on disk. When the process holding that descriptor exits — cleanly, on a crash, or after kill -9 — the kernel closes the descriptor and the lock is released. There is no lock file to delete afterward and no stale-lock problem to recover from. This is the single biggest reason to prefer flock over the old if [ -f /tmp/job.lock ] pattern, which leaves a dead file behind whenever the job is killed.
There are two ways to invoke it:
- Command form:
flock -n LOCKFILE COMMAND.flockopensLOCKFILE, takes the lock, and runsCOMMANDas a child. WhenCOMMANDfinishes,flockexits and the lock drops. This is the form you put directly in a crontab line. - File-descriptor form: inside a script you open a descriptor yourself with a redirect (
exec 200>/path/to/lock) and then callflock -n 200. The lock lives as long as descriptor 200 stays open, which is the rest of the script. This form lets you log a skip precisely and run several commands under one lock.
The behavior when the lock is already held is set by which of three modes you pick:
-n(non-blocking): if the lock is taken, fail immediately with exit code 1 and do not run the command. This is what you want in cron — an overlapping tick is skipped, not delayed.-w SECONDS(wait then give up): wait up toSECONDSfor the lock, then fail with exit code 1 if it never comes free. Use this when a short overlap is fine but an unbounded pile-up is not.- Default (block forever): with neither flag,
flockwaits indefinitely for the lock. In cron this is dangerous: blocked runs accumulate as parked processes, exactly the pile-up you were trying to avoid.
Step-by-step
-
Start from the crontab line that can overlap. This runs a backup every five minutes with no guard:
# Runs every 5 minutes; a slow run will overlap the next tick */5 * * * * /usr/local/bin/backup.sh -
Wrap it with
flock -nand a lock file. Use an absolute path toflockbecause cron’sPATHis minimal:# flock -n refuses to start if the lock is already held */5 * * * * /usr/bin/flock -n /var/lock/mybackup.lock /usr/local/bin/backup.shNow, if a run started at 03:00 is still going at 03:05, the 03:05 copy calls
flock, finds the lock held, and exits without touchingbackup.sh. -
Watch the second instance refuse to start. Reproduce it by hand. Hold the lock for five minutes in the background, then try again:
flock -n /var/lock/mybackup.lock sleep 300 & flock -n /var/lock/mybackup.lock echo "second run" echo "exit code: $?"Expected output — the
echo "second run"never runs, andflockreports failure:exit code: 1 -
Stop cron from emailing every skipped run. By default a skipped run exits 1, and cron mails that non-zero exit to the job owner as if it were a failure. Add
-E 0soflockexits 0 when it cannot get the lock with-n:# -E 0: a skipped run is not a failure, so cron stays quiet */5 * * * * /usr/bin/flock -n -E 0 /var/lock/mybackup.lock /usr/local/bin/backup.shWith
-E 0, only a real error frombackup.shproduces a non-zero exit and a cron mail. A skipped overlap exits cleanly. -
Use the file-descriptor form inside the script when you want to log skips. The command form cannot tell “skipped” apart from “the job ran and failed”, because both surface as a non-zero exit. Opening the descriptor yourself fixes that:
#!/usr/bin/env bash set -euo pipefail exec 200>/var/lock/mybackup.lock if ! flock -n 200; then echo "$(date -Is) another run holds the lock; skipping" >&2 exit 0 fi # Real work runs here, holding fd 200 for the whole block /usr/local/bin/do-backupDescriptor 200 stays open until the script exits, so the lock covers every command after the
flockcall. Theexit 0on a skip means cron treats it as success. -
Add a bounded wait when a short overlap is acceptable. If you would rather wait a little than skip outright, replace
-nwith-w:# Wait up to 30s for the lock, then give up */5 * * * * /usr/bin/flock -w 30 /var/lock/mybackup.lock /usr/local/bin/backup.shflockwaits up to 30 seconds; if the lock frees up in that window the job runs, otherwise it exits 1 (or 0 with-E 0). Never drop the flag entirely — plainflock LOCKFILE COMMANDblocks forever and reintroduces the pile-up. -
Log a skip from the crontab line itself if you cannot edit the script. The command form can still record skips, with one caveat:
*/5 * * * * /usr/bin/flock -n /var/lock/mybackup.lock /usr/local/bin/backup.sh || echo "$(date -Is) backup skipped or failed" >> /var/log/backup.logThe caveat:
||fires on any non-zero exit, so this line also logs genuine backup failures under the same message. When you need to tell a skip apart from a failure, use the descriptor form from step 5.
Validate it works
-
Take the lock and hold it. In one terminal, grab the lock for five minutes:
flock -n /var/lock/mybackup.lock sleep 300 -
Try to acquire it while held. In a second terminal, attempt the same lock:
flock -n /var/lock/mybackup.lock echo ran echo $?Expected — nothing prints from
echo ran, and the exit code is 1:1 -
See who holds it.
lsofshows the process on the lock file:lsof /var/lock/mybackup.lockExpected — a
flock/sleepprocess with the file open:COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME flock 48213 root 3w REG 259,2 0 12583091 /var/lock/mybackup.lock -
Confirm the lock auto-releases. Let the first job end (or
Ctrl-Cthesleep), then retry in the second terminal:flock -n /var/lock/mybackup.lock echo ranExpected — the command runs now that the descriptor from the first job is closed:
ran
Troubleshooting
- The lock never seems to release. Usually the job backgrounds a child that inherits and keeps the descriptor open, so the lock outlives the parent. Make sure the long-running work runs in the foreground under the lock, or that any daemon it starts closes inherited descriptors. A related trap: do not point the lock at a file the command itself truncates or recreates — lock a dedicated file such as
/var/lock/mybackup.lock, not the data file the job rewrites. flock: command not found. Minimal container images and some stripped-down distros omit util-linux. Install it (apt-get install -y util-linux,apk add util-linux, ordnf install util-linux) and use the absolute path in cron.- Locking on NFS or an unusual filesystem.
flock(2)locks are local to the host and do not coordinate across machines over NFS, and older NFS setups may not honor them at all. Keep the lock file on a local filesystem such as/var/lock,/run/lock, or/tmp— never on a shared mount you expect other hosts to respect. - Cron emails an alert on every skipped run. That is the default exit-1 behavior surfacing through cron’s mail. Add
-E 0(command form) orexit 0on the skip path (descriptor form) so a correctly skipped run is not treated as a failure. - One lock file shared by unrelated jobs. Two different jobs pointed at the same lock will block each other for no reason. Give each job its own lock file named after the job.
When this is the wrong approach
- Locking across multiple hosts.
flockonly coordinates processes on one machine. To keep a job single across a fleet, use a real distributed lock — a database advisory lock (for example Postgrespg_advisory_lock), a lease in Consul or etcd, or a Redis lock — not a file on local disk. - A job that should really be a long-running service. If the work is effectively continuous, a systemd service (which cannot start a second copy of the same unit) is a better fit than cron plus a lock. See cron vs systemd timers and systemd timers vs cron for the trade-offs.
- When overlap is genuinely fine. If two copies of the job can run at once without corrupting data or wasting meaningful resources, adding a lock is complexity you do not need.
For the exact flag semantics and exit codes, keep the flock(1) manual page handy.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.