You are here

public function JobScheduler::perform in Job Scheduler 8.2

Same name and namespace in other branches
  1. 8.3 src/JobScheduler.php \Drupal\job_scheduler\JobScheduler::perform()

Perform periodic jobs.

Return value

array Result of perform periodic jobs.

Throws

\Exception Exceptions thrown by code called by this method are passed on.

Overrides JobSchedulerInterface::perform

File

src/JobScheduler.php, line 202

Class

JobScheduler
Manage scheduled jobs.

Namespace

Drupal\job_scheduler

Code

public function perform() {
  $timestamp = $this->time
    ->getRequestTime();

  // Reschedule stuck periodic jobs after one hour.
  $this->database
    ->update('job_schedule')
    ->fields([
    'scheduled' => 0,
  ])
    ->condition('scheduled', $timestamp - 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 = 0;
  $failed = 0;
  $jobs = $this->database
    ->select('job_schedule', NULL, [
    'fetch' => \PDO::FETCH_ASSOC,
  ])
    ->fields('job_schedule')
    ->condition('scheduled', 0)
    ->condition('next', $timestamp, '<=')
    ->orderBy('next', 'ASC')
    ->range(0, 200)
    ->execute();
  foreach ($jobs as $job) {
    $job['data'] = unserialize($job['data']);
    try {
      $this
        ->dispatch($job);
    } catch (\Exception $e) {
      watchdog_exception('job_scheduler', $e);
      $failed++;

      // Drop jobs that have caused exceptions.
      $this
        ->remove($job);
    }
    $total++;
    if (time() > $start + 30) {
      break;
    }
  }
  return [
    'start' => $start,
    'total' => $total,
    'failed' => $failed,
  ];
}