3 namespace Drupal\automated_cron\EventSubscriber;
5 use Drupal\Core\Config\ConfigFactoryInterface;
6 use Drupal\Core\CronInterface;
7 use Drupal\Core\State\StateInterface;
8 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9 use Symfony\Component\HttpKernel\Event\PostResponseEvent;
10 use Symfony\Component\HttpKernel\KernelEvents;
13 * A subscriber running cron after a response is sent.
15 class AutomatedCron implements EventSubscriberInterface {
20 * @var \Drupal\Core\CronInterface
25 * The cron configuration.
27 * @var \Drupal\Core\Config\Config
32 * The state key value store.
34 * @var \Drupal\Core\State\StateInterface
39 * Constructs a new automated cron runner.
41 * @param \Drupal\Core\CronInterface $cron
43 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
45 * @param \Drupal\Core\State\StateInterface $state
46 * The state key-value store service.
48 public function __construct(CronInterface $cron, ConfigFactoryInterface $config_factory, StateInterface $state) {
50 $this->config = $config_factory->get('automated_cron.settings');
51 $this->state = $state;
55 * Run the automated cron if enabled.
57 * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
58 * The Event to process.
60 public function onTerminate(PostResponseEvent $event) {
61 $interval = $this->config->get('interval');
63 $cron_next = $this->state->get('system.cron_last', 0) + $interval;
64 if ((int) $event->getRequest()->server->get('REQUEST_TIME') > $cron_next) {
71 * Registers the methods in this class that should be listeners.
74 * An array of event listener definitions.
76 public static function getSubscribedEvents() {
77 return [KernelEvents::TERMINATE => [['onTerminate', 100]]];