This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

[Cyber Week Savings] Unleash the power of managed cloud hosting at 40% OFF for 4 months. GET THE DEAL

Magento 2 Cron Job: How to Create, Set up, and Configure It in Easy Steps

Updated on November 1, 2022

10 Min Read
Magento Corn Job

Managing any ecommerce store can be a serious challenge. There is always a long list of tasks to do, and it seems that almost every task is urgent; chances are that you may not be able to perform all of them simultaneously. So how would you tackle this challenge?

The answer lies in Magento Cron Jobs!

If you’re a developer or a store owner who wants to save time and automate tasks, then Magento cron jobs come in handy. A cron job allows you to create and execute commands and tasks at predefined intervals, dates, and times.

Since cron jobs reduce time and effort, it’s equally important to know when to use them. In this article, I’ll tell you the use cases and how you can create and configure Magento cron jobs using two different methods.

When to Use Magento Cron Jobs?

For a typical Magento store, cron jobs take care of many mundane tasks that take up much of the developer’s time. These are some of the example tasks that Magento cron jobs can automate:

  • Sending newsletter emails;
  • Indexing and caching;
  • Sitemap generation;
  • Auto-updates of currency rates;

Magento developers can use cron jobs to automate almost all tasks to improve the store’s overall operations.

Set up Cron Jobs in Magento 2

By default, the Magento cron job is integrated into the platform’s core. You can add and schedule tasks in the Magento module for execution at a regular predefined time. Magento executes all the cron tasks using cron.php and cron.sh files, located at the root of the Magento store.

All you need to do is ensure that your server-level cron module can run the Magento cron file. If you don’t have a server to try out setting up a cron job, sign up for a free trial on Cloudways to have experience running cron jobs.

Managed Magento Hosting for an Instant Performance Boost

Add & schedule cron jobs with absolute ease on the fastest cloud hosting platform.

Before Magento 2 Cron Configuration

Before configuring Magento 2 cron, you must carry out certain steps to ensure setting up and executing cron jobs goes smoothly.

Log in to the Magento 2 server as a master user (who has permission to write to the Magento 2 file system). If you use the Bash shell, you can use the following command to switch to the Magento file system owner:

su <Magento 2 file system owner> -s /bin/bash -c <command>

Creating Magento 2 Cron Job

To create a Magento 2 cron job, you must log in as a user with root privileges (as mentioned earlier) and run the following command:

crontab -u <Magento 2 file system owner user name> -e

For example, if the username is magento_cloudways, the command would be

crontab -u magento_cloudways -e

Now since the following commands are long and there is a chance of a mistake, I recommend using a text editor.

*/1 * * * * php -c <ini-file-path> <your Magento install dir>/bin/magento cron:run

*/1 * * * * php -c <ini-file-path> <your Magento install dir>/update/cron.php

*/1 * * * * php -c <ini-file-path> <your Magento install dir>/bin/magento setup:cron:run

The first command reindexes the indexers, sends automated emails and generates the sitemap. This command is associated with the PHP command line .ini file.

The other two commands are used for the Component Manager and System Upgrade.

Example:

*/1 * * * * /usr/bin/php -c /etc/php5/apache2/php.ini /var/www/magento2/bin/magento cron:run > /var/www/magento2/var/log/magento.cron.log&

*/1 * * * * /usr/bin/php -c /etc/php5/apache2/php.ini /var/www/magento2/update/cron.php > /var/www/magento2/var/log/update.cron.log&

*/1 * * * * /usr/bin/php -c /etc/php5/apache2/php.ini /var/www/magento2/bin/magento setup:cron:run > /var/www/magento2/var/log/setup.cron.log&

Now save all changes to the crontab.

Configure Cron Jobs From Admin Panel

The Magento application provides the following cron groups:

  • Default, which contains most cron jobs
  • Index, which refreshes indexers
  • Consumers, which runs message queue consumers

Follow the below steps to configure the default and index group:

  • Log in to the Magento 2 Admin, navigate to Stores → Settings → Configuration.
  • Navigate to Advanced → System and expand the Cron (Scheduled Tasks) section and perform further on the Cron configuration options for the group:index and Cron configuration options for the group:default sections.

configure-cron-job

  • Set the values of Cron configuration options for the group:index as shown below:

configure-cron-group-index

  • Set the values of Cron configuration options for the group:default as shown below:

setup-cron-default-group

When complete, click Save Config.

Create Custom Cron Jobs in Magento 2

In this section, I’ll discuss how to create a custom cron job program to perform scheduled tasks of your module.

Prerequisites of Magento 2 Store

  • The Magento application is installed in /var/www/html/magento2;
  • Your Magento database username and password are both magento;
  • Rights to perform all actions as the file system owner.

Step 1: Create a Sample Module

To create the custom cron job, you just need to create a custom sample module. If you already have a sample module, you can skip this step and continue with your sample module.

Step 2: Create a Class to Run a Cron Job

Follow the below steps:

  • Create a Cron directory inside your module root directory, i.e., app/code/Cloudways/SampleModule/Cron.
  • Create a sample class within the Cron directory to create the cron job. This class will write a row to the cron_schedule table that confirms it’s been set up successfully.
  • Create a file name SampleCron.php, i.e., app/code/Cloudways/SampleModule/Cron/SampleCron.php, and copy the following code:
<?php
Namespace Cloudways\SampleModule\Cron;

use Psr\Log\LoggerInterface;

class SampleCron {
    protected $logger;

    public function __construct(LoggerInterface $logger) {
        $this->logger = $logger;
    }

   /**
    * Write to system.log
    *
    * @return void
    */
    public function execute() {
        $this->logger->info('Cron Works');
    }
}

Step 3: Create crontab.xml File

Create crontab.xml as follows in the magento2/app/code/Cloudways/SampleModule/etc. directory and copy the following code:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="custom_cronjob" instance="Cloudways\SampleModule\Cron\SampleCron" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

Where,

  • group_name: Name of the cron group. The group name doesn’t have to be unique. You can run cron for one group at a time.
  • job_name: Unique ID for this cron job.
  • classpath: Class to be instantiated (classpath).
  • method: Method in the classpath to call.
  • time: Schedule in cron format. Omit this parameter if the schedule is defined in the Magento database or other storage. Consider the following graph:
* * * * * command to be executed

| | | | |

| | | | +----- Day of week (0 - 7) (Sunday=0 or 7)

| | | +------- Month (1 - 12)

| | +--------- Day of the month (1 - 31)

| +----------- Hour (0 - 23)

+------------- Minute (0 - 59)

The crontab.xml runs the instance Cloudways\SampleModule\Cron\SampleCron.php class once per minute.

Step 4: Compile the Code and Clean the Cache

Let’s compile the code with the following command:

bin/magento setup:di:compile

And clean the cache with the following command:

bin/magento cache:clean

Step 5: Verify the Cron Job

This step shows how to successfully verify the custom cron job using a SQL query on the cron_schedule database table.

Run the following command:

bin/magento cron:run

Step 6: Set up Magento 2 Cron Group (Optional)

If you wish to set up a cron group for a custom module Magento. You have the option of either using the default or a different group.

  1. To configure the cron group for your module, open the crontab.xml file in the text editor;
  2. Change <group id=”default”> to <group id=”custom_crongroup”>;
  3. Exit the text editor.
<config>    
      <group id="custom_crongroup">
<job name="<job_name>" instance="<classpath>" method="<method>">
    <schedule><time></schedule>
</job>
      </group>
</config>

In the above code:

  • <group_name> is the cron group name. Remember that you can only run cron for a single group at a time.

4: Create /var/www/html/magento2/app/code/Magento/SampleMinimal/etc/cron_groups.xml with the following contents:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/cron_groups.xsd">
    <group id="custom_crongroup">
        <schedule_generate_every>1</schedule_generate_every>
        <schedule_ahead_for>4</schedule_ahead_for>
        <schedule_lifetime>2</schedule_lifetime>
        <history_cleanup_every>10</history_cleanup_every>
        <history_success_lifetime>60</history_success_lifetime>
        <history_failure_lifetime>600</history_failure_lifetime>
        <use_separate_process>1</use_separate_process>
    </group>
</config>

This will create the custom cron group, run the below command to run the cron job with the custom cron group created:

bin/magento cron:run --group="custom_crongroup"

Run Cron Jobs on the Command Line

The following command allows you to run cron on Magento 2 command line:

magento cron:run [--group="<cron group name>"]

The –group switch defines the cron group to run. You can remove it if you wish to use the default group.

Note: You may run cron for one group at a time. You must run cron twice, the first time to discover the tasks to run, and the second time, to run the tasks themselves).

Run Cron In The Background

Magento CE and EE editions have a recommended process for executing Magento 2 cron jobs.

Cron Job Requirements

Magento cron job is run with different configurations. The general cron job that reindexes, generates emails and sitemap usually runs as the PHP command-line users php.ini. Other cron jobs are used by the component manager and system upgrade utilities. These commands must be used in the web servers, php.ini

If you don’t have experience with running cron, you can use all commands with the web server’s configuration.

Web Server Configuration

To find out the web server configuration, run the phpinfo.php file in the web browser and search for the loaded configuration file option.

PHP command-line

After web server configuration, you need to do the PHP command-line configuration by the following command:

php -i | grep php.ini

As a result you get something like this:

Configuration File (php.ini) Path => /etc/php5/cli

Loaded Configuration File => /etc/php5/cli/php.ini

Disable Magento 2 Cron Jobs

Magento 2 doesn’t have a default feature to disable cron jobs like observers. However, to disable the cron job for the above module you created in Magento 2, there’s a technique to schedule a time that contains a date that never happens.

Follow the below steps:

1. Open the crontab.xml file;

2. Select the job name you want to disable; let’s say we want to disable the custom_cronjob created above.

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
<group id="default">
    <job name="custom_cronjob" instance="Cloudways\SampleModule\Cron\SampleCron" method="execute">
        <schedule>* * * * *</schedule>
    </job>
</group>
</config>

3. To disable the cron job, change the schedule value to 0 0 30 2 *, i.e., 31 Feb.

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
<group id="default">
    <job name="custom_cronjob" instance="Cloudways\SampleModule\Cron\SampleCron" method="execute">
        <schedule>0 0 30 2 *</schedule>
    </job>
</group>
</config>

Now, the custom_cronjob cron job has been set to run at 00:00 on the February 30, at a date that will never occur.

Helpful Commands for Cron Jobs

Though Magento 2 cron runs by a schedule, there are some useful commands you might need to configure manually.

For those cases, you need the most common commands to use with Magento cron:

To create crontab: bin/magento cron:install
To check crontab: crontab -l
To remove all Magento cron of this user: crontab -r
To run the cron job: bin/magento cron:run
To run cron group: bin/magento cron:run –group [cron group name]
For example:
bin/magento cron:run –group index
bin/magento cron:run –group default
To remove Magento crontab: bin/magento cron:remove

For instance, I can set up a cron job configuration to update currency rates for visitors coming from different countries. Here is a complete article on how to schedule a currency update task with Magento cron job

Optimize Magento Speed Like a Pro

Subscribe now and get a free ebook to your inbox.

Thank You

Your Ebook is on it’s Way to Your Inbox.

How to Set Up Cron Job on a Cloudways

Log into the Cloudways Platform with your credentials and click Applications in the top menu bar. Select the application for which you want to set up the cron job.

Magento cron job Cloudways app console

Go to the Cron Job Management section and click the Add New Cron Job button.

Magento cron job Cloudways app console

Next, you have to configure the cron job. For that, you need to decide how often the cron job will run by selecting a value from the dropdown menu (you can enter a value of your own as well).

You can also set the type of script that you will be running (PHP, cURL, or Wget) and the command to execute. Click Submit to save your settings.

Magento cron job management

If you want to use the command line, you can switch to the advanced editor under the Advanced tab.

Magento cron job advanced

Now if you want to monitor the currently active and running cron jobs, click Monitoring in the left menu bar, click Analytics, and choose Running Crons from the given choices.

Magento cron job monitoring

Summary

For online store owners, it is a huge time saver to not get sidetracked by tasks that could be automated. Why not focus on your core strength, selling? This is why Magento 2 cron jobs are an easy option to manage tasks on Magento Hosting by Cloudways. Try it by starting your free trial today. If you run into any issues, you can contact 24/7/365 Support, who will help you with any issue.

I hope you have found this article useful in setting up cron jobs. If you want me to add any custom Magento cron job, please do let me know in the comment section.

Magento 2 Cron Job FAQs

Q. What is Magento 2 cron job?

Magento cron job — is one of the most important Magento 2 features. It helps to configure commands or scripts that systematically run and perform the tasks you intend it to. With the cron job you don’t need to manually reindex, generate google sitemaps, send Magento emails, update currency rates etc.

Q. How can I tell if a cron job is running Magento?

To verify whether or not your crontab is set up do the following steps: Log in to your Magento server as, or switch to, the Magento file system owner. See if the following file exists: bash ls -al /var/. setup_cronjob_status If the file exists, cron has run successfully in the past.

Q. How do I remove the cron job in Magento 2?

To remove the Magento cron job:

  1. Log in as, or switch to, the Magento file system owner in the terminal
  2. Change to your Magento installation directory: cd /
  3. Enter the following command: php bin/magento cron:remove
Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Great speed, features, knowledgebase, dashboard, UX and fast, expert support. Very happy!”

Stefan [Management Consultant]

Jyotishna Kumari

Jyotishina is the Magento Community Expert at Cloudways and has 4 years of experience in web development. She has worked on e-commerce sites since the turn of the millennium and was working with Magento before version 1 was released. She loves to travel and explore new ideas whenever she finds time. Get in touch with her at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Unleash The Cloud.
Not Budgets.

For 4 Months +
Up To 30 Free Migrations

Cyber Week

SAVINGS
Time Left In Offer
  • 0

    Days

  • 0

    Hours

  • 0

    Minutes

  • 0

    Seconds

40% OFF

On All Plans

GET THE DEAL NOW