Working With The Magento Cron

January 27, 2023
January 27, 2023
Alex Jackson

Introduction

Magento 2 production sites need to have cron jobs inserted into the user’s crontab so that it can automatically run periodic tasks such as reindexing. This is an essential part of a production site and fairly simple to install and configure. Below we’ll go over adding them, removing them, configuring them, and running them manually.

Adding a new cron job

To add a new cron job, log into the server via SSH. Navigate to the directory where your Magento files are located, and run the following command as the user which owns your site files:

$ php ./bin/magento cron:install

This won’t affect other cron jobs in the crontab. The cron job installed will be nested between lines starting with #~ MAGENTO START and #~ MAGENTO END. Below is an example of how it may look:

#~ MAGENTO START 331fbc6015f350cf7dff747c7ed018c87067ca89479cf2a1337b1a351e97d797
* * * * * /usr/bin/php7.4 /path/to/example.com/html/bin/magento cron:run 2>&1 | grep -v "Ran jobs by schedule" >> /path/to/example.com/html/var/log/magento.cron.log
#~ MAGENTO END 331fbc6015f350cf7dff747c7ed018c87067ca89479cf2a1337b1a351e97d797

The /path/to/example/example.com/html will be different depending on where your site files are, as will the hash after #~ MAGENTO START and #~MAGENTO END.

Removing a cron job

To remove a previously installed cron job, simply log in to the server as detailed above and run the following command:

$ php bin/magento cron:remove

Configuring Magento cron jobs

To configure Magento cron jobs, log in to the admin panel and navigate to Stores > Settings > Configuration. On the left-hand sidebar, open the Advanced drop-down menu and select System. This will open an interface with a Cron (Scheduled Tasks) dropdown with nested drop-downs showing configuration options.

Running cron job manually

To run specific Magento cron jobs in a group manually, log into your server as the site files owner and run command:

$ php bin/magento cron:run --group <group>

Where <group> is any cron job group, such as index, default, or consumers. You will likely have other cron job groups as defined by your custom Magento crons and those of plugins. These groups can be viewed within the admin panel at the same location as described in the section, Configuring Magento cron jobs.

Caveats

Keep in mind it’s best to temporarily disable Magento cron jobs when performing updates. Although they often do not cause issues, they can potentially cause a race condition and prevent an update from succeeding.

Further reading

  • Official documentation on CLI commands for Magento 2 crons can be found here.
  • Official documentation on custom Magento 2 crons can be found here
  • Information about scheduling cron jobs non-specific to Magento can be found here