You are here

function poormanscron_run_cron_check in Poormanscron 5.2

Same name and namespace in other branches
  1. 6.2 poormanscron.module \poormanscron_run_cron_check()

Menu callback; executes cron via an image callback.

This callback runs cron in a separate HTTP request to prevent "mysterious" slow-downs of regular HTTP requests. It is invoked via an AJAX request (if the client's browser supports JavaScript).

See also

poormanscron_run_cron_check_access()

1 string reference to 'poormanscron_run_cron_check'
poormanscron_menu in ./poormanscron.module
Implements hook_menu().

File

./poormanscron.module, line 67
A module which runs Drupal cron jobs without the cron application.

Code

function poormanscron_run_cron_check() {
  $time = time();
  $cron_run = FALSE;
  $cron_threshold = variable_get('cron_safe_threshold', 10800);

  // Cron threshold semaphore is used to avoid errors every time the image
  // callback is displayed when a previous cron is still running.
  $threshold_semaphore = variable_get('cron_threshold_semaphore', FALSE);
  if ($threshold_semaphore) {
    if ($time - $threshold_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', t('Cron has been running for more than an hour and is most likely stuck.'), WATCHDOG_ERROR);

      // Release the cron threshold semaphore.
      variable_del('cron_threshold_semaphore');
    }
  }
  else {

    // Run cron automatically if it has never run or threshold was crossed.
    $cron_last = variable_get('cron_last', 0);
    if ($time - $cron_last > $cron_threshold) {

      // Force the current user to anonymous to ensure consistent permissions
      // on cron runs.
      session_save_session(FALSE);
      $original_user = $GLOBALS['user'];
      $GLOBALS['user'] = drupal_anonymous_user();

      // Lock cron threshold semaphore.
      variable_set('cron_threshold_semaphore', $time);

      // Run cron!
      $cron_run = drupal_cron_run();

      // Release the cron threshold semaphore.
      variable_del('cron_threshold_semaphore');

      // Restore the user.
      $GLOBALS['user'] = $original_user;
      session_save_session(TRUE);
      if ($cron_run) {

        // Truncate the page cache so that cached pages get a new timestamp for
        // the next cron run.
        cache_clear_all('*', 'cache_page', TRUE);
      }
    }
  }
  $cron_last = variable_get('cron_last', 0);
  drupal_set_header('Expires: ' . gmdate('D, d M Y H:i:s O', $cron_last + $cron_threshold));

  // @todo Should we allow this to be cached?
  exit;
}