You are here

function job_scheduler_cron in Job Scheduler 7.2

Same name and namespace in other branches
  1. 8.3 job_scheduler.module \job_scheduler_cron()
  2. 8.2 job_scheduler.module \job_scheduler_cron()
  3. 6 job_scheduler.module \job_scheduler_cron()
  4. 7 job_scheduler.module \job_scheduler_cron()

Implements hook_cron().

File

./job_scheduler.module, line 137
Main file for the Job Scheduler.

Code

function job_scheduler_cron() {

  // Reschedule all jobs if requested.
  if (variable_get('job_scheduler_rebuild_all', FALSE)) {
    foreach (job_scheduler_info() as $name => $info) {
      job_scheduler_rebuild_scheduler($name, $info);
    }
    variable_set('job_scheduler_rebuild_all', FALSE);
    return;
  }

  // Reschedule stuck periodic jobs after one hour.
  db_update('job_schedule')
    ->fields(array(
    'scheduled' => 0,
  ))
    ->condition('scheduled', REQUEST_TIME - 3600, '<')
    ->condition('periodic', 1)
    ->execute();

  // Query and dispatch scheduled jobs.
  // Process a maximum of 200 jobs in a maximum of 30 seconds.
  $start = time();
  $total = $failed = 0;
  $jobs = db_select('job_schedule', NULL, array(
    'fetch' => PDO::FETCH_ASSOC,
  ))
    ->fields('job_schedule')
    ->condition('scheduled', 0)
    ->condition('next', REQUEST_TIME, '<=')
    ->orderBy('next', 'ASC')
    ->range(0, 200)
    ->execute();
  foreach ($jobs as $job) {
    $job['data'] = unserialize($job['data']);
    try {
      JobScheduler::get($job['name'])
        ->dispatch($job);
    } catch (Exception $e) {
      watchdog('job_scheduler', $e
        ->getMessage(), array(), WATCHDOG_ERROR);
      $failed++;

      // Drop jobs that have caused exceptions.
      JobScheduler::get($job['name'])
        ->remove($job);
    }
    $total++;
    if (time() > $start + 30) {
      break;
    }
  }

  // If any jobs were processed, log how much time we spent processing.
  if ($total || $failed) {
    watchdog('job_scheduler', 'Finished processing scheduled jobs (!time, !total total, !failed failed).', array(
      '!time' => format_interval(time() - $start),
      '!total' => $total,
      '!failed' => $failed,
    ));
  }
}