View source
<?php
namespace Drupal\rng;
use Drupal\Core\Queue\QueueFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\rng\Entity\RuleSchedule;
class RngCron {
protected $ruleSchedulerQueue;
protected $ruleSchedulerStorage;
public function __construct(QueueFactory $queue_factory, EntityTypeManagerInterface $entity_type_manager) {
$this->ruleSchedulerQueue = $queue_factory
->get('rng_rule_scheduler', FALSE);
$this->ruleSchedulerStorage = $entity_type_manager
->getStorage('rng_rule_scheduler');
}
public function hook_cron() {
$this
->scheduleRules();
$this
->deleteScheduleRules();
}
protected function scheduleRules() {
$ids = $this->ruleSchedulerStorage
->getQuery()
->condition('trigger_date', time(), '<=')
->condition('in_queue', 0, '=')
->condition('attempts', RuleSchedule::ATTEMPTS_MAX, '<=')
->execute();
$rule_schedules = $this->ruleSchedulerStorage
->loadMultiple($ids);
foreach ($rule_schedules as $rule_schedule) {
$data = [
'rule_scheduler_id' => $rule_schedule
->id(),
];
if ($this->ruleSchedulerQueue
->createItem($data)) {
$rule_schedule
->setInQueue(TRUE)
->save();
if ($component = $rule_schedule
->getComponent()) {
if ($rule = $component
->getRule()) {
$rule
->setIsActive(FALSE)
->save();
}
}
}
}
}
protected function deleteScheduleRules() {
$ids = $this->ruleSchedulerStorage
->getQuery()
->condition('attempts', RuleSchedule::ATTEMPTS_MAX, '>')
->execute();
$rule_schedules = $this->ruleSchedulerStorage
->loadMultiple($ids);
$this->ruleSchedulerStorage
->delete($rule_schedules);
}
}