hook_cron

Versions
4.6 – 7
hook_cron()

Perform periodic actions.

This hook will only be called if cron.php is run (e.g. by crontab).

Modules that require to schedule some commands to be executed at regular intervals can implement hook_cron(). The engine will then call the hook at the appropriate intervals defined by the administrator. This interface is particularly handy to implement timers or to automate certain tasks. Database maintenance, recalculation of settings or parameters are good candidates for cron tasks.

Short-running or not resource intensive tasks can be executed directly.

Long-running tasks should use the queue API. To do this, one or more queues need to be defined via hook_cron_queue_info(). Items that need to be processed are appended to the defined queue, instead of processing them directly in hook_cron(). Examples of jobs that are good candidates for hook_cron_queue_info() include automated mailing, retrieving remote data, and intensive file tasks.

See also

hook_cron_queue_info()

Return value

None.

Related topics

Code

modules/system/system.api.php, line 194

<?php
function hook_cron() {
  // Short-running operation example, not using a queue:
  // Delete all expired records since the last cron run.
  $expires = variable_get('mymodule_cron_last_run', REQUEST_TIME);
  db_delete('mymodule_table')
    ->condition('expires', $expires, '>=')
    ->execute();
  variable_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 = DrupalQueue::get('aggregator_feeds');
  foreach ($result as $feed) {
    $queue->createItem($feed);
  }
}
?>
Login or register to post comments
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.