How to Create Cron Job in Magento 2

In this article, we will learn how to create cron job in Magento. Magento uses Cron Jobs to run scheduled tasks, reindexing, generating emails, newsletters, sitemaps and much more.

Cron job is a great feature by Linux, the free operating system for the user. The cron job will create a command or a script that is appropriate with the task you want to do. Instead of manual working, the cronjob allows running automatically in exact time and date.

In this example, we are using a sample module with Kaushik as the Vendor name and HelloWorld as the module name.

Step 1: Create crontab.xml

File: app/code/Kaushik/HelloWorld/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="Kaushik\HelloWorld\Cron\Test" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>
  • group id is your cron group name. You can run only cron for single group at a time.
  • job instance is class to be instantiated.
  • job method is method in job instance to call.
  • job name is Unique ID for this cron job.
  • schedule is schedule in cron format where
* * * * * 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 2: Create a class to run cron

File: app/code/Kaushik/HelloWorld/Cron/Test.php

<?php
namespace Kaushik\HelloWorld\Cron;

use \Psr\Log\LoggerInterface;
class Test {
  protected $logger;

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

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

In the above code, we created a log. Once the cron is executed, the contents of the ‘execute’ method will be added in the system.log file.

Step 3: Run the cron job

We can run the Magento cron jobs using the below command.

php bin/magento cron:run

I hope this is useful blog for you.

Thank you for reading!

Leave a Reply