W3cubDocs

/Drupal 8

function hook_cron

hook_cron()

Perform periodic actions.

Modules that require some commands to be executed periodically can implement hook_cron(). The engine will then call the hook whenever a cron run happens, as defined by the administrator. Typical tasks managed by hook_cron() are database maintenance, backups, recalculation of settings or parameters, automated mailing, and retrieving remote data.

Short-running or non-resource-intensive tasks can be executed directly in the hook_cron() implementation.

Long-running tasks and tasks that could time out, such as retrieving remote data, sending email, and intensive file tasks, should use the queue API instead of executing the tasks directly. To do this, first define one or more queues via a \Drupal\Core\Annotation\QueueWorker plugin. Then, add items that need to be processed to the defined queues.

Related topics

Hooks
Define functions that alter the behavior of Drupal core.

File

core/core.api.php, line 1894
Documentation landing page and topics, plus core library hooks.

Code

function hook_cron() {
  // Short-running operation example, not using a queue:
  // Delete all expired records since the last cron run.
  $expires = \Drupal::state()->get('mymodule.cron_last_run', REQUEST_TIME);
  db_delete('mymodule_table')
    ->condition('expires', $expires, '>=')
    ->execute();
  \Drupal::state()->set('mymodule.cron_last_run', REQUEST_TIME);

  // Long-running operation example, leveraging a queue:
  // Fetch feeds from other sites.
  $result = db_query('SELECT * FROM {aggregator_feed} WHERE checked + refresh < :time AND refresh <> :never', array(
    ':time' => REQUEST_TIME,
    ':never' => AGGREGATOR_CLEAR_NEVER,
  ));
  $queue = \Drupal::queue('aggregator_feeds');
  foreach ($result as $feed) {
    $queue->createItem($feed);
  }
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!core.api.php/function/hook_cron/8.1.x