How to Create a Cron Job in Drupal

How to Create a Cron Job in Drupal

Step 1: Configure Drupal's Built-in Cron

Drupal has a built-in cron system. To configure it, navigate to:

Admin > Configuration > System > Cron

Set the frequency and save the configuration.

Step 2: Create a Custom Cron Hook

To define a custom cron job, implement hook_cron() in a custom module:

function mymodule_cron() {
    \Drupal::logger('mymodule')->notice('Custom cron job executed.');
    // Add your scheduled task logic here
}

Step 3: Run Cron Manually

You can trigger cron manually using Drush:

drush cron

Or via the browser:

https://yourwebsite.com/cron.php

Step 4: Set Up a System Cron Job

On your server, open the crontab editor:

crontab -e

Add the following line to run Drupal cron every hour:

0 * * * * wget -O - -q -t 1 https://yourwebsite.com/cron.php

Step 5: Verify the Cron Job

Check the logs to ensure the cron job is running:

drush watchdog:show --type=cron

Conclusion

Now your Drupal cron job is successfully set up and will run automatically based on the defined schedule.

0 Comments