How to Create Cron Job in Magento 2

How to Create Cron Job in Magento 2
May 20, 2020 490 view(s)
How to Create Cron Job in Magento 2

Magento 2 Cron Job is setting an automatic schedule on time, which is really convenient when you run Magento 2 store. For example, you need assistance from software like website statistics or content management systems which require running at a certain time, however, maybe you are unavailable to do that. That is why you must create the Cron Job on your web server.

This post is all for you. The simple and clear instructions will be mentioned here.

What is a Cron Job?
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 the exact time and date. Due to its automation, the cron jobs are the perfect choice for repeated projects every day or every week.

Cron configuration is very important in Magento to set the schedule for many system activities such as reindexing, auto-update of currency rates, Magento emails, etc. Only when the configuration is correct, the cron job is active.

How to install cron job

Create crontab.xml

File: app/code/Magezend/CronTest/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 instance="Magezend\CronTest\Cron\Test" method="execute" name="magezend_crontest_cron">
     <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 (classpath).
  • - job method is method in job instance to call.
  • - job name is Unique ID for this cron job.
  • - schedule is schedule in cron format. The following graph shows what it consists of:
  • 
    * * * * * 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)
    
    
    

    All done, please flush cache and run magento cron:run --group="default" from the command line.