How To Set / Configure Custom Cron Jobs In Magento 2

Cron job is a great feature which is used to do the specific task automatically in exact time and date without manual working. The cron job is the perfect choice to do the repeated action every date or every week.

Magento 2 uses cron jobs for,

  • Catalog price rules
  • Newsletters
  • Generating Google sitemaps
  • Reindexing
  • Automatic updating of currency rates
  • All Magento emails (including order confirmation and transactional)

and more.

In Magento 2, we can create crons easily and it will be listed in the database table (table name: cron_schedule) to process our tasks in scheduled time.

Step 1: Create a sample module

Create a new custom module based on the Magento 2 structure or you can use the existing module. For a new module, create a registration.php file in the below file path,

File Path: app/code/BlogTreat/CustomCron/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'BlogTreat_CustomCron',
    __DIR__
);

Create a module.xml file in the below file path to define new Magento 2 module

File Path: app/code/BlogTreat/CustomCron/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="BlogTreat_CustomCron" setup_version="1.0.0">
    </module>
</config>

Step 2: Create a class to run cron

Create CronFile.php file in the below file path.

File Path: app/code/BlogTreat/CustomCron/Cron/CronFile.php

This file contains the custom cron code and which will be executed while the cron runs in Magento 2.

<?php
namespace BlogTreat\CustomCron\Cron;

use \Psr\Log\LoggerInterface;

class CronFile {

    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

Create a crontab.xml file in the following file path and set a time schedule to run the custom cron code which is defined in the CronFile.php.

File Path: app/code/BlogTreat/CustomCron/etc/crontab.xml

<?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="BlogTreat\CustomCron\Cron\CronFile" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

The above code runs the “execute” method in BlogTreat\CustomCron\Cron\CronFile.php class once per minute, resulting in a row being added to the cron_schedule table.

Here,

  • group id: is a cron group name.
  • job name: is a Unique ID for this cron job.
  • instance: is a class to be instantiated (classpath).
  • method: is a method in job instance to call.
  • schedule: is a schedule in cron format.
* * * * * command to be executed
| | | | |
| | | | +----- Day of week (0 - 7) (Sunday=0 or 7)
| | | +------- Month (1 - 12)
| | +--------- Day of month (1 - 31)
| +----------- Hour (0 - 23)
+------------- Minute (0 - 59)

Step 4: Run the cron job

After completing the above steps run the below SSH command in your Magento 2 installed root directory to run the Magento 2 cron jobs

php bin/magento cron:run

To check whether the cron is working properly, go to <Magento 2 root directory>var/log/system.log and you will see the text “Cron Works” in it.

Step 5: Create custom cron group

To create custom cron group, create cron_groups.xml file in the below file path,

File Path: app/code/BlogTreat/CustomCron/etc/cron_groups.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:BlogTreat_CustomCron: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>
    </group>
</config>

Open crontab.xml in a text editor and change <group id=”default”> to <group id=”custom_crongroup”> then save the file.

Now you can run the below SSH command in your Magento 2 installed root directory to run the Magento 2 custom cron group

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

To verify, log in to the Magento 2 admin panel and navigate to Stores > Configuration > Advanced > System > Cron (Scheduled Tasks). Here, you can see “Cron configuration options for group: custom_crongroup” as follows,

Creating & Running Cron Jobs in Magento 2 Custom Module

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *