Limit the number of instances of a PHP CRON Script

I have data coming into a Queue that I needs to be processed by a “worker” process. One option is to set this up as a daemon.

Another is to run a CRON that starts every minute, process the data and dies. If there is a large amount of data, a second worker starts a minute later, and a third a minute after that – adfinitum.

The problem is we need to limit the number of instances that can run at the same time, or we’ll crash the server.

Here’s how… in this case it is at the top of a “drush” script. We need to know the name of the script.

$max_instances = 6;
$name_of_script = 'worker.newdata.drush.php';

exec("ps aux | grep '" . escapeshellarg($name_of_script) . "'", $results);
// nb 2 lines for system
if (count($results) > $max_instances + 2) {
    drush_print("Already Running Maximum ({$max_instances}) Instances");
    exit ;

You should also be able to use the __FILE__ variable in PHP, but this is causing an error in Drupal.

Leave a Reply