Definition

hook_cron()
drupal/modules/system/system.api.php, line 344

Description

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 hook_cron_queue_info()

Return value

None.

Related topics

Namesort iconDescription
HooksAllow modules to interact with the Drupal core.

Code

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);
  }
}