Magento 2: Create Custom Cron

Magento 2 create custom cron -sbdevblog

Do we need to create a custom cron job? Let’s do it.

In any case, we need to perform certain operations frequently. We will require a cron. The best example is the indexer. As we have seen, we must set the indexer state to update by schedule to optimise performance.

Similarly, we need to create a custom cron to perform activities defined in the logic of our custom module.

So let’s look into it.

Magento 2: Create Custom Cron

Firstly, we must create crontab.xml inside the etc directory of the module.

<?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="sbdevblog_cron" instance="SbDevBlog\Crons\Cron\SbDevBlogCron" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

Here, the id of the group is set as default. However, we may also specify the custom ID of the group as given below.

<group id="sbdevblog_group">

In the case of a custom group, we must create a cron_groups.xml file. The cron_groups.xml defines the schedule frequency, history clean-up, history failure and success lifetime, and so on for that specific cron group.

Tags under the group tagDescription
schedule_generate_everyRecurrence (in minutes) that timetables are composed in the cron_schedule table
schedule_ahead_forTime (in minutes) before timetables are composed in the cron_schedule table.
schedule_lifetime
The time window (in minutes) after which cron work must start, or it will be deemed missed (or “past the point of no return” to run).
history_cleanup_everyTime (in minutes) for which the database retains the cron history.
history_success_lifetimeThe time (in minutes) that the database retains a record of successfully executed cron jobs
history_failure_lifetimeThe time (in minutes) for the database records that failed cron jobs
use_separate_processRun the tasks for this cron group in a different PHP process.

So, Let’s create a cron_group.xml file.

<?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="sbdevblog_group">
        <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>

The custom cron group is in admin under Stores > Settings > Configuration > Advanced > System.

The job tag of the crontab.xml file contains the below attributes:

AttributesDescription
nameThe name of the cron
instanceSpecify a class instance that defines the actual logic to perform the task.
methodSpecify the method of the instance class that is responsible for executing the task.

The schedule tag defines the frequency as minute, hour, day/month, month, week/day.

Finally, we must create an instance class defined as an instance attribute.

Magento 2: Create a Custom Cron Class

<?php
/**
 * @copyright Copyright (c) sbdevblog (https://www.sbdevblog.com)
 */
namespace SbDevBlog\Crons\Cron;

use Psr\Log\LoggerInterface;

class SbDevBlogCron
{
    /**
     * @var LoggerInterface
     */
    private LoggerInterface $logger;

    /**
     * Constructor
     *
     * @param LoggerInterface $logger
     */
    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * Cron job
     *
     * @return void
     */
    public function execute(): void
    {
        $this->logger->info("Cron Job Executed");
    }
}

Run cron by using the command.

Command to run cron:
    php bin/magento cron:run

Run specific group
    php bin/magento cron:run --group=GROUP

That’s it. Thanks for reading sbevblog; please use a comment box to provide suggestions. Also, please subscribe and share with your connections.

Click here to create a custom message queue.

Download Source Code

Note: Please verify the code of this blog and the relevant git repository before using it in production.
sb dev blog adobe commece Magento 2

🙂 HAPPY CODING 🙂

2 thoughts on “Magento 2: Create Custom Cron

Leave a Reply

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