← Tous les articles

PHP: stop a cron job from running twice at the same time

A sync scheduled every 5 minutes that sometimes takes 7 will eventually overlap with itself. flock(), a MySQL lock or the flock command: which one to pick, and the traps to avoid.

PHP: stop a cron job from running twice at the same time

Key points

  • A marker file that exists or not is fragile: it stays behind after a crash.
  • flock() with LOCK_NB releases itself automatically when the process dies.
  • Across several servers you need a shared lock, such as MySQL’s GET_LOCK().

Here is the usual story. A PHP script pushes orders to an ERP every five minutes. One day the remote API is slow, the run takes seven minutes, and the next cron run starts while the first is still going. Orders get sent twice and stock is decremented twice. When a client tells us about a duplicate that happened “just once this month”, an overlapping job is the first thing we check.

Why a marker file is not enough

The first instinct is to create running.lock at the start and delete it at the end. That holds until the script crashes, gets killed or runs out of memory. The file stays, and no run ever starts again. Usually nobody notices until a customer asks why nothing has synced for three days.

What you want is a lock held by the process itself, which the operating system drops the moment the process goes away, for whatever reason.

One server: flock()

flock() puts an exclusive lock on an open file. With LOCK_NB it does not wait: if it fails, another run is in progress and the script exits cleanly.

<?php
// bin/sync-orders.php, launched every 5 minutes by crontab
$lock = fopen(__DIR__ . '/../var/sync-orders.lock', 'c');
if ($lock === false) {
    fwrite(STDERR, "Cannot open lock filen");
    exit(1);
}

if (!flock($lock, LOCK_EX | LOCK_NB)) {
    // The previous run is still working: leave quietly
    exit(0);
}

ftruncate($lock, 0);
fwrite($lock, (string) getmypid()); // handy when debugging

try {
    syncOrders();
} finally {
    flock($lock, LOCK_UN);
    fclose($lock);
}

The file can stay on disk forever. What matters is the lock, not whether the file exists. If the process is killed, the OS closes the descriptor and the lock goes with it.

A trap we have hit: open the file inside a helper function, let $lock go out of scope, and PHP closes the file, releasing the lock while the job is still running. Keep the handle alive until the very end.

Several servers: a shared lock

Once the app runs on two machines behind a load balancer, each has its own disk and flock() protects nothing. Do not rely on it over network file systems either. If MySQL or MariaDB is already there, GET_LOCK() does the job:

$got = $pdo->query("SELECT GET_LOCK('sync-orders', 0)")->fetchColumn();
if ((int) $got !== 1) {
    exit(0); // another server holds the lock
}

try {
    syncOrders($pdo);
} finally {
    $pdo->query("SELECT RELEASE_LOCK('sync-orders')");
}

The lock belongs to the database connection and is released when it closes. The flip side: if the connection drops during a long job (a wait_timeout, for instance), the lock vanishes and the script has no idea. Split long jobs into short batches.

No code change at all

On Linux, the flock command wraps any script straight from the crontab. We add timeout so a stuck run cannot hold the lock forever:

*/5 * * * * flock -n /var/lock/sync-orders.lock timeout 20m php /srv/app/bin/sync-orders.php

It is the fastest way to make a legacy script safe while you plan a proper fix.

FAQ

Does WP-Cron have the same problem?

WP-Cron sets its own lock, but it is triggered by page views and can start a long task more than once on a busy site. For heavy jobs we disable it and run it from the system cron, with a lock.

What should the script do when the lock is taken?

Exit with code 0 and ideally log it. If that happens often, the job is too long for its interval.

Scheduled jobs creating duplicates or silently stopping? We audit and harden background processing in PHP and WordPress applications.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →