Cron semaphore

Sometimes you want to avoid running massive operations during cron run, then you might want to at least first check if it is running. When cron runs it sets a variable called cron_semaphore in the variable table. Remember that cron still can start when your script is running.

<?php

//Fetch the cron semaphore
$semaphore = variable_get('cron_semaphore', FALSE);

if (!
$semaphore) {
  
//Then run my code
}
?>

Here is the cron run function from Drupal 6 core file common.inc

<?php
/**
 * Executes a cron run when called
 * @return
 * Returns TRUE if ran successfully
 */
function drupal_cron_run() {
 
// Try to allocate enough time to run all the hook_cron implementations.
 
if (function_exists('set_time_limit')) {
    @
set_time_limit(240);
  }

 
// Fetch the cron semaphore
 
$semaphore = variable_get('cron_semaphore', FALSE);

  if (
$semaphore) {
    if (
time() - $semaphore > 3600) {
     
// Either cron has been running for more than an hour or the semaphore
      // was not reset due to a database error.
     
watchdog('cron', 'Cron has been running for more than an hour and is most likely stuck.', array(), WATCHDOG_ERROR);

     
// Release cron semaphore
     
variable_del('cron_semaphore');
    }
    else {
     
// Cron is still running normally.
     
watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
    }
  }
  else {
   
// Register shutdown callback
   
register_shutdown_function('drupal_cron_cleanup');

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

   
// Iterate through the modules calling their cron handlers (if any):
   
module_invoke_all('cron');

   
// Record cron time
   
variable_set('cron_last', time());
   
watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);

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

   
// Return TRUE so other functions can check if it did run successfully
   
return TRUE;
  }
}
?>
Knowledge keywords: