// Delete all expired records since the last cron run.
$expires = \Drupal::state()->get('mymodule.last_check', 0); $request_time = \Drupal::time()->getRequestTime(); \Drupal::database()->delete('mymodule_table') ->condition('expires', $expires, '>=') ->execute(); \Drupal::state()->set('mymodule.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('mymodule.feeds'); $ids = \Drupal::entityTypeManager()->getStorage('mymodule_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('mymodule_feed') ->accessCheck(FALSE) ->condition('queued', $request_time - (3600 * 6), '<') ->execute();