Cron.php 6.76 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core;

5
use Drupal\Component\Utility\Timer;
6
use Drupal\Core\Extension\ModuleHandlerInterface;
7
use Drupal\Core\Queue\QueueWorkerManagerInterface;
8
use Drupal\Core\Queue\RequeueException;
9
use Drupal\Core\State\StateInterface;
10 11
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\Core\Queue\QueueFactory;
12
use Drupal\Core\Session\AnonymousUserSession;
13
use Drupal\Core\Session\AccountSwitcherInterface;
14
use Drupal\Core\Queue\SuspendQueueException;
15
use Psr\Log\LoggerInterface;
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

/**
 * The Drupal core Cron service.
 */
class Cron implements CronInterface {

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The lock service.
   *
   * @var \Drupal\Core\Lock\LockBackendInterface
   */
  protected $lock;

  /**
   * The queue service.
   *
   * @var \Drupal\Core\Queue\QueueFactory
   */
  protected $queueFactory;

  /**
   * The state service.
   *
46
   * @var \Drupal\Core\State\StateInterface
47 48 49
   */
  protected $state;

50
  /**
51
   * The account switcher service.
52
   *
53
   * @var \Drupal\Core\Session\AccountSwitcherInterface
54
   */
55
  protected $accountSwitcher;
56

57 58 59 60 61 62 63
  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

64 65 66 67 68 69 70
  /**
   * The queue plugin manager.
   *
   * @var \Drupal\Core\Queue\QueueWorkerManagerInterface
   */
  protected $queueManager;

71 72 73 74 75 76 77 78 79
  /**
   * Constructs a cron object.
   *
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock service.
   * @param \Drupal\Core\Queue\QueueFactory $queue_factory
   *   The queue service.
80
   * @param \Drupal\Core\State\StateInterface $state
81
   *   The state service.
82 83
   * @param \Drupal\Core\Session\AccountSwitcherInterface $account_switcher
   *    The account switching service.
84 85
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
86
   * @param \Drupal\Core\Queue\QueueWorkerManagerInterface $queue_manager
87
   *   The queue plugin manager.
88
   */
89
  public function __construct(ModuleHandlerInterface $module_handler, LockBackendInterface $lock, QueueFactory $queue_factory, StateInterface $state, AccountSwitcherInterface $account_switcher, LoggerInterface $logger, QueueWorkerManagerInterface $queue_manager) {
90 91 92 93
    $this->moduleHandler = $module_handler;
    $this->lock = $lock;
    $this->queueFactory = $queue_factory;
    $this->state = $state;
94
    $this->accountSwitcher = $account_switcher;
95
    $this->logger = $logger;
96
    $this->queueManager = $queue_manager;
97 98 99 100 101 102 103 104 105 106 107
  }

  /**
   * {@inheritdoc}
   */
  public function run() {
    // Allow execution to continue even if the request gets cancelled.
    @ignore_user_abort(TRUE);

    // Force the current user to anonymous to ensure consistent permissions on
    // cron runs.
108
    $this->accountSwitcher->switchTo(new AnonymousUserSession());
109 110 111 112 113 114 115

    // Try to allocate enough time to run all the hook_cron implementations.
    drupal_set_time_limit(240);

    $return = FALSE;

    // Try to acquire cron lock.
116
    if (!$this->lock->acquire('cron', 900.0)) {
117
      // Cron is still running normally.
118
      $this->logger->warning('Attempting to re-run cron while it is already running.');
119 120
    }
    else {
121 122
      $this->invokeCronHandlers();
      $this->setCronLastTime();
123 124 125 126 127 128 129 130

      // Release cron lock.
      $this->lock->release('cron');

      // Return TRUE so other functions can check if it did run successfully
      $return = TRUE;
    }

131 132 133 134
    // Process cron queues.
    $this->processQueues();

    // Restore the user.
135
    $this->accountSwitcher->switchBack();
136 137 138 139 140 141 142 143 144 145

    return $return;
  }

  /**
   * Records and logs the request time for this cron invocation.
   */
  protected function setCronLastTime() {
    // Record cron time.
    $this->state->set('system.cron_last', REQUEST_TIME);
146
    $this->logger->notice('Cron run completed.');
147 148 149 150 151 152 153
  }

  /**
   * Processes cron queues.
   */
  protected function processQueues() {
    // Grab the defined cron queues.
154
    foreach ($this->queueManager->getDefinitions() as $queue_name => $info) {
155
      if (isset($info['cron'])) {
156 157 158 159
        // Make sure every queue exists. There is no harm in trying to recreate
        // an existing queue.
        $this->queueFactory->get($queue_name)->createQueue();

160
        $queue_worker = $this->queueManager->createInstance($queue_name);
161 162
        $end = time() + (isset($info['cron']['time']) ? $info['cron']['time'] : 15);
        $queue = $this->queueFactory->get($queue_name);
163 164
        $lease_time = isset($info['cron']['time']) ?: NULL;
        while (time() < $end && ($item = $queue->claimItem($lease_time))) {
165
          try {
166
            $queue_worker->processItem($item->data);
167 168
            $queue->deleteItem($item);
          }
169 170 171 172
          catch (RequeueException $e) {
            // The worker requested the task be immediately requeued.
            $queue->releaseItem($item);
          }
173 174 175 176 177 178 179 180 181 182
          catch (SuspendQueueException $e) {
            // If the worker indicates there is a problem with the whole queue,
            // release the item and skip to the next queue.
            $queue->releaseItem($item);

            watchdog_exception('cron', $e);

            // Skip to the next queue.
            continue 2;
          }
183
          catch (\Exception $e) {
184 185
            // In case of any other kind of exception, log it and leave the item
            // in the queue to be processed again later.
186 187 188 189 190
            watchdog_exception('cron', $e);
          }
        }
      }
    }
191
  }
192

193 194 195 196
  /**
   * Invokes any cron handlers implementing hook_cron.
   */
  protected function invokeCronHandlers() {
197 198
    $module_previous = '';

199 200
    // Iterate through the modules calling their cron handlers (if any):
    foreach ($this->moduleHandler->getImplementations('cron') as $module) {
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

      if (!$module_previous) {
        $this->logger->notice('Starting execution of @module_cron().', [
          '@module' => $module,
        ]);
      }
      else {
        $this->logger->notice('Starting execution of @module_cron(), execution of @module_previous_cron() took @time.', [
          '@module' => $module,
          '@module_previous' => $module_previous,
          '@time' => Timer::read('cron_' . $module_previous) . 'ms',
        ]);
      }
      Timer::start('cron_' . $module);

216 217 218 219 220 221 222
      // Do not let an exception thrown by one module disturb another.
      try {
        $this->moduleHandler->invoke($module, 'cron');
      }
      catch (\Exception $e) {
        watchdog_exception('cron', $e);
      }
223 224 225

      Timer::stop('cron_' . $module);
      $module_previous = $module;
226
    }
227 228 229 230 231 232
    if ($module_previous) {
      $this->logger->notice('Execution of @module_previous_cron() took @time.', [
        '@module_previous' => $module_previous,
        '@time' => Timer::read('cron_' . $module_previous) . 'ms',
      ]);
    }
233 234 235
  }

}