Skip to content

Prevent overlapping cron jobs with flock so a slow run never stacks

A practitioner guide to flock cron: exclusive vs non-blocking locks, the -w timeout, exit codes, and how to wrap a cron entry so a slow run never overlaps the next scheduled one.

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 with flock --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.

Timeline showing run 1 holding the lock while run 2 is refused by flock -n and run 3 acquires the freed lock

There are two ways to invoke it:

  • Command form: flock -n LOCKFILE COMMAND. flock opens LOCKFILE, takes the lock, and runs COMMAND as a child. When COMMAND finishes, flock exits 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 call flock -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 to SECONDS for 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, flock waits 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

  1. 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
  2. Wrap it with flock -n and a lock file. Use an absolute path to flock because cron’s PATH is 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.sh

    Now, 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 touching backup.sh.

  3. 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, and flock reports failure:

    exit code: 1
  4. 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 0 so flock exits 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.sh

    With -E 0, only a real error from backup.sh produces a non-zero exit and a cron mail. A skipped overlap exits cleanly.

  5. 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-backup

    Descriptor 200 stays open until the script exits, so the lock covers every command after the flock call. The exit 0 on a skip means cron treats it as success.

  6. Add a bounded wait when a short overlap is acceptable. If you would rather wait a little than skip outright, replace -n with -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.sh

    flock waits 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 — plain flock LOCKFILE COMMAND blocks forever and reintroduces the pile-up.

  7. 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.log

    The 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

  1. Take the lock and hold it. In one terminal, grab the lock for five minutes:

    flock -n /var/lock/mybackup.lock sleep 300
  2. 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
  3. See who holds it. lsof shows the process on the lock file:

    lsof /var/lock/mybackup.lock

    Expected — a flock/sleep process 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
  4. Confirm the lock auto-releases. Let the first job end (or Ctrl-C the sleep), then retry in the second terminal:

    flock -n /var/lock/mybackup.lock echo ran

    Expected — 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, or dnf 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) or exit 0 on 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. flock only coordinates processes on one machine. To keep a job single across a fleet, use a real distributed lock — a database advisory lock (for example Postgres pg_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.