Magento 2 Guide: How to Create a Cron Job

Magento2
Motilal Kumawat February 19, 2024

Cron jobs in Magento 2 are essential for automating repetitive tasks like sending emails, updating currency rates, generating sitemap, cleaning logs, and more. Instead of performing tasks manually, you can schedule them to run automatically at a specific time. In this guide, we’ll walk you through the process of creating a custom cron job in Magento 2.

What is a Cron Job in Magento 2?

A cron job is a scheduled task that runs automatically at predefined intervals. Magento 2 relies heavily on cron jobs to handle various background activities such as:

  • Reindexing
  • Order and invoice email notifications
  • Newsletters
  • Cache cleaning
  • Currency rate updates

Step 1: Create Module Skeleton

First, create a custom module. For this example, we’ll use Mavenbird_CronExample.

app/code/Mavenbird/CronExample/
├── registration.php
├── etc/module.xml
├── etc/crontab.xml
├── Cron/CustomCron.php
    

registration.php

<?php
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Mavenbird_CronExample',
    __DIR__
);
    

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="Mavenbird_CronExample" setup_version="1.0.0" />
</config>
    

Step 2: Define Cron Job

Create a crontab.xml file in etc/ to schedule the cron job.

<?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="mavenbird_custom_cron" 
             instance="Mavenbird\CronExample\Cron\CustomCron" 
             method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>

</config>
    

The schedule * * * * * means the cron will run every minute. You can adjust it like Linux cron syntax:

  • 0 * * * * → Every hour
  • 0 0 * * * → Every day at midnight
  • */5 * * * * → Every 5 minutes

Step 3: Create Cron Class

Now, create the cron class in Cron/CustomCron.php.

<?php
namespace Mavenbird\CronExample\Cron;

use Psr\Log\LoggerInterface;

class CustomCron
{
    protected $logger;

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

    public function execute()
    {
        $this->logger->info('Mavenbird custom cron executed successfully!');
        return $this;
    }
}
    

This will log a message each time the cron runs. You can check logs in var/log/system.log.

Step 4: Enable Module

php bin/magento setup:upgrade
php bin/magento cache:flush
    

Step 5: Run Magento Cron

Ensure your Magento cron job is set up on the server. Run this command in the Magento root:

php bin/magento cron:run
    

If configured correctly, you’ll see the log entry in var/log/system.log.

Best Practices for Magento 2 Cron Jobs

  • Always use LoggerInterface for debugging.
  • Keep cron jobs lightweight and avoid long-running tasks.
  • Use queues (RabbitMQ, MySQL queue) for heavy processes.
  • Test with php bin/magento cron:run before relying on system scheduler.
  • Never overload crontab.xml with too many jobs; spread them wisely.

Conclusion

Cron jobs are a vital part of Magento 2 that allow you to automate tasks and improve store efficiency. With this step-by-step guide, you now know how to create, configure, and test your own cron jobs in Magento 2.

Ready to Transform Your eCommerce?

Whether you're launching something new or transforming an existing venture, Mavenbird is here to help bring your ideas to life.

Loading...

Talk to an Expert

Request a Free Quote and expert consultation.