flock Safety

flock safety is the practice of wrapping cron jobs and scheduled scripts with the Linux flock command to prevent multiple simultaneous instances from running and causing resource conflicts or data corruption.
CronflockLinuxConcurrencySchedulingDevOps

flock is a Linux utility that acquires a file-based advisory lock before executing a command. It ensures that only one instance of a script runs at any given time, even if cron schedules overlapping runs.

Without flock safety, a long-running cron job (backup, report generation, data sync) can be scheduled to run every 5 minutes. If the job takes 7 minutes, by the 5-minute mark a second instance starts running concurrently. Both instances compete for the same resources, write to the same files, and produce corrupted output.

flock Syntax

Non-blocking (skip if already running): flock -n /tmp/jobname.lock /path/to/script.sh
Blocking (wait up to 10 seconds): flock -w 10 /tmp/jobname.lock /path/to/script.sh
In crontab: */5 * * * * flock -n /tmp/backup.lock /usr/local/bin/backup.sh

Lock File Placement

Lock files are typically placed in /tmp/ or /var/run/. The filename should be unique per job to avoid unrelated jobs blocking each other. /tmp/ is cleared on reboot, so stale locks from crashed scripts are automatically removed on next boot.

Related Tools

Fix Guides

Frequently Asked Questions

What happens if a flock-protected job crashes?
If the script crashes, the lock file remains but the file descriptor lock is released automatically by the kernel when the process exits. The next cron invocation can acquire the lock normally. Stale lock files in /tmp/ do not prevent re-execution.
Should I use flock -n or flock -w?
Use flock -n (non-blocking) for jobs that should skip if already running — backups, report generation, cleanup scripts. Use flock -w TIMEOUT for jobs that should wait — database migrations, deployment scripts where you want the next run to proceed once the current run finishes.
How do I add flock safety to all my cron jobs?
ConfigClarity's Cron Visualiser has a flock safety toggle. After analysing your crontab, enable flock safety to generate flock-wrapped versions of all your jobs with unique lock file names.