You are here

public function JobScheduler::cron in Job Scheduler 6

Periodic cron task.

File

./JobScheduler.inc, line 87
JobScheduler class.

Class

JobScheduler
Handle adding and removing jobs from schedule.

Code

public function cron() {

  // Check and set scheduler semaphore, take time.
  if (variable_get('job_scheduler_cron', FALSE)) {
    watchdog('JobScheduler', 'Last cron process did not finish.', array(), WATCHDOG_ERROR);
  }
  variable_set('job_scheduler_cron', TRUE);
  $start = time();

  // Reschedule stuck periodic jobs after one hour.
  db_query("UPDATE {job_schedule} SET scheduled = 0 WHERE scheduled < %d AND periodic = 1", JOB_SCHEDULER_REQUEST_TIME - 3600);

  // Query and dispatch scheduled jobs.
  $num = module_exists('drupal_queue') ? variable_get('job_schedule_queue_num', 200) : variable_get('job_schedule_num', 5);
  $result = db_query_range("SELECT * FROM {job_schedule} WHERE scheduled = 0 AND next < %d ORDER BY next ASC", JOB_SCHEDULER_REQUEST_TIME, 0, $num);
  while ($job = db_fetch_array($result)) {

    // Flag periodic jobs as scheduled, remove one-off jobs.
    if ($job['periodic']) {
      $job['scheduled'] = $job['last'] = JOB_SCHEDULER_REQUEST_TIME;
      $job['next'] = $job['period'] + JOB_SCHEDULER_REQUEST_TIME;
      drupal_write_record('job_schedule', $job, array(
        'callback',
        'type',
        'id',
      ));
    }
    else {
      $this
        ->remove($job);
    }

    // Queue job if there is a queue declared for it, otherwise execute it.
    if (function_exists($job['callback'])) {
      if (!$this
        ->queue($job)) {
        $job['callback']($job);
      }
    }
  }

  // Unflag and post a message that we're done.
  variable_set('job_scheduler_cron', FALSE);
  watchdog('JobScheduler', 'Finished processing schedule after !time.', array(
    '!time' => format_interval(time() - $start),
  ));
}