Skip to content

Command-line cron for Drupal

We have over 100 sites setup in a multi-site shared code-base environment. Cron runs every 10 minutes on every site. In order to prevent saturating our bandwidth with frequent cron calls, we setup a command-line php script that bootstraps Drupal and invokes cron. This has very little overhead since it bypasses HTTP.

You can place the file in the drupal root, then run it by calling:
> php cron-cli.php mysite.com

Here’s what the code looks like:


<?php
if (!$_SERVER['argc']) {
  die("No arguments.");
}

$_SERVER['HTTP_HOST'] = $_SERVER['argv'][1];
$_SERVER['SCRIPT_NAME'] = '/'.$_SERVER['SCRIPT_NAME'];

ini_set('memory_limit', '256M');
ini_set('max_execution_time', 300); // Needed for feedapi to work!

include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$semaphore = variable_get('cron_semaphore', FALSE);
if ($semaphore) {
  if (time() - $semaphore > 1200) {
      // Either cron has been running for more than 20 min or the semaphore
      // was not reset due to a database error.

      // Release cron semaphore
      variable_del('cron_semaphore');
    }
  else {
    die("Attempting to re-run cron while it is already running. $semaphore\n");
  }
}

// Lock cron semaphore
variable_set('cron_semaphore', time());

echo $_SERVER['HTTP_HOST']."\n";

$modules = module_implements('cron');

foreach($modules as $module) {
  echo "Invoking cron for $module... ";
  module_invoke($module,'cron');
  $time = time();
  echo $time."\n";
  flush();
}

variable_set('cron_last', $time);
echo "\n";

// Release cron semaphore
variable_del('cron_semaphore');

{ 2 } Comments

  1. jadwigo | November 18, 2009 at 3:47 am | Permalink

    Thanks for this, it helped me out a lot.

    I also have a modified version of your script now.
    http://www.jadwigo.nl/blog/jadwigo/drupal_cron_from_commandline

    The differences are: my version also works from the webserver and it tells you when you forget the hostname from the commandline.

  2. Gunnar | December 11, 2009 at 2:02 pm | Permalink

    Install Drush - http://drupal.org/project/drush

    Then just drush cron

Post a Comment

Your email is never published nor shared. Required fields are marked *