Skip to main content

QueueWorker

Displaying 1 - 1 of 1

Cron is a daemon

Cron is a daemon that executes commands at specified intervals. 
These commands are called "cron jobs". 
Cron is available on Unix, Linux, and Mac servers. 
Windows servers use a Scheduled Task to execute commands. 
The actual "cron job" is a time-triggered action that is usually (and most efficiently) performed by your website's hosting server, but can also be configured by a remote server or even from your desktop.

function mymodule_cron() {

  // Short-running operation example, not using a queue:
  // Delete all expired records since the last cron run.
  $expires = \Drupal::state()->get('my_module.last_check', 0);
  $request_time = \Drupal::time()->getRequestTime();
  \Drupal::database()
    ->delete('my_module_table')
    ->condition('expires', $expires, '>=')
    ->execute();
  \Drupal::state()->set('my_module.last_check', $request_time);

  // Long-running operation example, leveraging a queue:
  // Queue news feeds for updates once their refresh interval has elapsed.
  $queue = \Drupal::queue('my_module.feeds');
  $ids = \Drupal::entityTypeManager()
    ->getStorage('my_module_feed')
    ->getFeedIdsToRefresh();
  foreach (Feed::loadMultiple($ids) as $feed) {
    if ($queue->createItem($feed)) {

      // Add timestamp to avoid queueing item more than once.
      $feed->setQueuedTime($request_time);
      $feed->save();
    }
  }
  $ids = \Drupal::entityQuery('my_module_feed')
    ->accessCheck(FALSE)
    ->condition('queued', $request_time - 3600 * 6, '<')
    ->execute();
  if ($ids) {
    $feeds = Feed::loadMultiple($ids);
    foreach ($feeds as $feed) {
      $feed->setQueuedTime(0);
      $feed->save();
    }
  }
}