comparison core/modules/automated_cron/src/EventSubscriber/AutomatedCron.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 129ea1e6d783
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\automated_cron\EventSubscriber;
4
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;
11
12 /**
13 * A subscriber running cron after a response is sent.
14 */
15 class AutomatedCron implements EventSubscriberInterface {
16
17 /**
18 * The cron service.
19 *
20 * @var \Drupal\Core\CronInterface
21 */
22 protected $cron;
23
24 /**
25 * The cron configuration.
26 *
27 * @var \Drupal\Core\Config\Config
28 */
29 protected $config;
30
31 /**
32 * The state key value store.
33 *
34 * @var \Drupal\Core\State\StateInterface;
35 */
36 protected $state;
37
38 /**
39 * Constructs a new automated cron runner.
40 *
41 * @param \Drupal\Core\CronInterface $cron
42 * The cron service.
43 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
44 * The config factory.
45 * @param \Drupal\Core\State\StateInterface $state
46 * The state key-value store service.
47 */
48 public function __construct(CronInterface $cron, ConfigFactoryInterface $config_factory, StateInterface $state) {
49 $this->cron = $cron;
50 $this->config = $config_factory->get('automated_cron.settings');
51 $this->state = $state;
52 }
53
54 /**
55 * Run the automated cron if enabled.
56 *
57 * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
58 * The Event to process.
59 */
60 public function onTerminate(PostResponseEvent $event) {
61 $interval = $this->config->get('interval');
62 if ($interval > 0) {
63 $cron_next = $this->state->get('system.cron_last', 0) + $interval;
64 if ((int) $event->getRequest()->server->get('REQUEST_TIME') > $cron_next) {
65 $this->cron->run();
66 }
67 }
68 }
69
70 /**
71 * Registers the methods in this class that should be listeners.
72 *
73 * @return array
74 * An array of event listener definitions.
75 */
76 public static function getSubscribedEvents() {
77 return [KernelEvents::TERMINATE => [['onTerminate', 100]]];
78 }
79
80 }