public function JobScheduler::perform in Job Scheduler 8.3
Same name and namespace in other branches
- 8.2 src/JobScheduler.php \Drupal\job_scheduler\JobScheduler::perform()
Perform periodic jobs.
Parameters
string $name: (optional) Name of the schedule to perform. Defaults to null.
int $limit: (optional) The number of jobs to perform. Defaults to 200.
int $time: (optional) How much time scheduler should spend on processing jobs in seconds. Defaults to 30.
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 200
Class
- JobScheduler
- Manage scheduled jobs.
Namespace
Drupal\job_schedulerCode
public function perform($name = NULL, $limit = 200, $time = 30) {
$storage = $this->jobScheduleStorage;
$timestamp = time();
// Reschedule stuck periodic jobs after one hour.
$query = $storage
->getQuery();
$query
->condition('scheduled', $timestamp - 3600, '<');
$query
->condition('periodic', 1);
if (!empty($name)) {
$query
->condition('name', $name);
}
$entity_ids = $query
->execute();
if (!empty($entity_ids)) {
$jobs = $storage
->loadMultiple($entity_ids);
foreach ($jobs as $job) {
$job
->setScheduled(0);
$job
->save();
}
}
// Query and dispatch scheduled jobs.
// Process a maximum of 200 jobs in a maximum of 30 seconds.
$start = time();
$total = 0;
$failed = 0;
$query = $storage
->getQuery();
$query
->condition('scheduled', 0);
$query
->condition('next', $timestamp, '<=');
if (!empty($name)) {
$query
->condition('name', $name);
}
$query
->sort('next', 'ASC');
$query
->range(0, $limit);
$entity_ids = $query
->execute();
if (!empty($entity_ids)) {
$jobs = $storage
->loadMultiple($entity_ids);
foreach ($jobs as $job) {
try {
$this
->dispatch($job);
} catch (\Exception $e) {
watchdog_exception('job_scheduler', $e);
$failed++;
// Drop jobs that have caused exceptions.
$job
->delete();
}
$total++;
if (time() > $start + $time) {
break;
}
}
}
return [
'start' => $start,
'total' => $total,
'failed' => $failed,
];
}