How do I stop overlapping cron runs?

On this page

Cron starts a job on schedule whether the last run has finished or not. A job that takes longer than its interval runs twice at once, and two copies of a backup or an import can corrupt data. Take a lock at the start, and let the scheduler skip or queue the late run.

How do I lock a shell job?

crontab
*/5 * * * * flock -n /var/lock/import.lock /usr/local/bin/import.sh && curl -fsS --retry 5 https://ping.cronmissed.com/5f0c1b2e-7a3d-4c8e-9b61-2d4f8a7e3c10

flock -n takes the lock or exits at once with a non-zero status when another copy holds it. Because of the &&, a skipped run sends no ping, which is the honest result. If skipped runs are normal, send /log instead of nothing, so you can see them.

What does each scheduler offer?

SchedulerControlWhat a late run does
Kubernetes CronJobconcurrencyPolicy: Allow, Forbid or ReplaceForbid counts the skipped schedule as missed
LaravelwithoutOverlapping()Skipped while the lock is held; the lock expires after 24 hours by default
node-cronnoOverlap: trueThe tick is skipped
APSchedulermax_instances, one by defaultCounted as a misfire
pg_cronOne instance per jobA second run is queued and starts when the first ends
RenderSingle-run guaranteeThe next scheduled run waits for the active run
RailwayNo termination of active runsThe new run is skipped
Vercel CronNone built inA second invocation can start while the first runs; use a lock

How does monitoring help?

A skipped or queued run is a late run, so a check with a start ping sees it either way. If a job regularly outlasts its interval, the start pings show a pattern: runs that begin late, or that never finish before the next begins. Raise the interval or fix the job, and set the grace for the real run time. See start and finish pings.

Sources

Questions and answers

Is overlapping always a problem?
No. Idempotent jobs, such as a refresh that can be run any number of times, may overlap harmlessly. Jobs that write, move or delete data usually must not.
Why use a lock file and not check for the process?
A lock held by the kernel disappears when the process dies, so a crash cannot leave a stale lock. A pid file or a ps check can be fooled by a recycled pid or a race.
Know the moment a job goes quiet

Create a check, add one curl to the job, and CronMissed alerts you when a ping is late or reports a failure.

Start monitoring