Avoiding Cron Job Collisions


#1

When running cron jobs, it’s important to ensure your script finishes before it’s run again. For instance, say you have a cron job that runs every 30 minutes, but, on some occasions, it takes 45 minutes to complete. If left unchecked, the script will run from min 0 to 45 and 30 -> 1:15 and 1:00 -> 1:45 etc. which has a high likelihood of causing issues.

A common way to prevent this is through the use of a lock file. When the script is first run, it creates a file and locks it. When the script is run again, if the lock is still in place, the script will skip running. Based on our example above, this would mean the script would run from min 0 to 45 but when it runs again at min 30, it’ll get skipped. So the end result would be running from min 0 to 45, skip min 30 and run from 1:00 to 1:45 etc.

<?php

// Use lock file to ensure script doesn't collide with iteself
$filePath = '/tmp/script-name-' . Site::getConfig('handle') . '.lock';

$fp = fopen($filePath, 'w+');

// Lock file
if (flock($fp, LOCK_EX | LOCK_NB)) {

    // Run script here

    // Release lock once finished
    flock($fp, LOCK_UN);
}

fclose($fp);