What is the proper way to run recreate function in a cron job?

Created on 6 October 2023, about 1 year ago
Updated 30 April 2024, 8 months ago

Problem/Motivation

I'm adding a cron job and I want to recreate the entity usage statistics. So I created the cron job to execute it once a week on Saturday.

Steps to reproduce

This is my setup:

  • Drupal 10.1.3
  • Server is Nginx 1.20.2
  • PHP 8.1.14

Proposed resolution

Is this good enough? This is inside the custom_module.module file

function _cron_job_callback() {
  $entityUsageBatchManager =\Drupal::service('entity_usage.batch_manager');
  $entityUsageBatchManager->recreate();
}

Remaining tasks

API changes

May you please advice what would be the best/proper solution for this?

💬 Support request
Status

Active

Component

Code

Created by

🇧🇴Bolivia alvarito75 Cochabamba

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @alvarito75
  • 🇮🇳India dev16.addweb

    Yes, your implementation looks good. Placing this code inside your custom_module.module file within the hook_cron() implementation will ensure that the recreate() method of the entity_usage.batch_manager service is called during each cron run.

    1.) Define the function
    2.) Implement hook_cron()
    3.) Call the function within hook_cron()
    4.) Set the cron frequency

    /**
     * Implements hook_cron().
     */
    function custom_module_cron() {
      // Recreate the entity usage batch manager service.
      $entityUsageBatchManager = \Drupal::service('entity_usage.batch_manager');
    
      // Call the recreate method if it exists.
      if (method_exists($entityUsageBatchManager, 'recreate')) {
        $entityUsageBatchManager->recreate();
      }
    }
    
Production build 0.71.5 2024