AutomatedCron.php 2.14 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\automated_cron\EventSubscriber\AutomatedCron.
6 7
 */

8
namespace Drupal\automated_cron\EventSubscriber;
9 10 11

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\CronInterface;
12
use Drupal\Core\State\StateInterface;
13 14 15 16 17
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
18
 * A subscriber running cron after a response is sent.
19
 */
20
class AutomatedCron implements EventSubscriberInterface {
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

  /**
   * The cron service.
   *
   * @var \Drupal\Core\CronInterface
   */
  protected $cron;

  /**
   * The cron configuration.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  /**
   * The state key value store.
   *
39
   * @var \Drupal\Core\State\StateInterface;
40 41 42 43
   */
  protected $state;

  /**
44
   * Constructs a new automated cron runner.
45 46 47 48 49
   *
   * @param \Drupal\Core\CronInterface $cron
   *   The cron service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
50
   * @param \Drupal\Core\State\StateInterface $state
51
   *   The state key-value store service.
52 53 54
   */
  public function __construct(CronInterface $cron, ConfigFactoryInterface $config_factory, StateInterface $state) {
    $this->cron = $cron;
55
    $this->config = $config_factory->get('automated_cron.settings');
56 57 58 59 60 61
    $this->state = $state;
  }

  /**
   * Run the automated cron if enabled.
   *
62
   * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
63 64 65
   *   The Event to process.
   */
  public function onTerminate(PostResponseEvent $event) {
66 67 68 69 70
    $interval = $this->config->get('interval');
    if ($interval > 0) {
      $cron_next = $this->state->get('system.cron_last', 0) + $interval;
      if ((int) $event->getRequest()->server->get('REQUEST_TIME') > $cron_next) {
        $this->cron->run();
71 72 73 74 75 76 77 78 79 80 81
      }
    }
  }

  /**
   * Registers the methods in this class that should be listeners.
   *
   * @return array
   *   An array of event listener definitions.
   */
  public static function getSubscribedEvents() {
82
    return [KernelEvents::TERMINATE => [['onTerminate', 100]]];
83 84 85
  }

}