Creating & Running Cron in Magento 2 Custom Module

This article shows how to create and run cronjob in a custom module in Magento 2.

Here, we will focus on creating / setting up / running cron for a custom Magento 2 module.

Let us suppose, we are developing a custom module named Iyngaran_DemoModule (app/code/Iyngaran/DemoModule). To define the cron settings for your custom module, you need to write the following code in app/code/Iyngaran/DemoModule/etc/crontab.xml.

app/code/Iyngaran/DemoModule/etc/crontab.xml

As you can see from above code, we have defined to run the execute method of class Demo (app/code/Iyngaran/DemoModule/Cron/Demo.php) every hour when the cronjob is run in the server. The group id is set as “default”. You can give it your custom name as well.

Here’s the basic content:

Here is our class file. We will just log some text to test if the cron is working properly. The log text is saved in var/log/debug.log.

app/code/Iyngaran/DemoModule/Cron/Demo.php

You can manually run cron from terminal/command line with the following command:


Run all cron jobs

If it doesn’t work (doesn’t create any entries in cron_schedule table) then try flushing cache first:

After you run the above command, you can check your database table named cron_schedule. This table has fields like job_code, status, messages, created_at, scheduled_at, executed_at, etc. So, by looking into this table, you can know about the status of all the cron jobs.

Hope this helps.

2 Comments

Leave a Reply

Your email address will not be published.


*


*