It is pretty common that a site needs to do something regularly, but not too often. Most frequently it is maintenance tasks done through hook_cron, like core's update_cron which limits how often it checks for new versions of a site's modules. The pattern is pretty simple - store a timestamp in the site's state when the task is executed, then before executing the task again check that the desired period has elapsed.
A colleague took another approach that I thought was interesting and worth polishing into a contrib module, so I created Periodic. Instead of each task needing to duplicate the code for storing and checking a timestamp, Periodic's cron task emits events for common periods of time which other modules can respond to as needed:
MyModuleEventSubscriber {
public static function getSubscribedEvents() {
$events = [];
$events[PeriodicEvents::HOUR] = ['hourlyTask'];
$events[PeriodicEvents::DAY] = ['dailyTask'];
return $events;
}
public function hourlyTask() {
// Do hourly task.
}
public function dailyTask() {
// Do daily task.
}
}
If a different interval is needed for a task, Periodic offers a service to check if execution should proceed:
function mymodule_cron() {
$periodicManager = \Drupal::service('periodic.manager');
// Limit task to every six hours.
if ($periodicManager->execute('mymodule.crontask', 21600)) {
// Do custom task.
}
}
Top comments (0)