F FreeCronJob
← Blog

How to Prevent Overlapping Cron Jobs with File-Based Locks

If a scheduled job runs longer than its interval, overlapping runs can duplicate webhooks and corrupt state.

Why overlaps happen

Most schedules assume each run is finished before the next one starts. That assumption fails under API delays or high queue load.

Implement a lock file

Use a short lock at job start and release it only when the run ends:

$lock = '/tmp/cron.lock';
$fp = fopen($lock, 'c+');
if (!flock($fp, LOCK_EX | LOCK_NB)) { exit('Already running'); }
try { /* job work */ } finally { flock($fp, LOCK_UN); fclose($fp); }
?>

What to monitor

  • Job runtime
  • Retry spikes
  • Downstream queue size

Linkuri utile