Home » Magento, Magento 227 June 2016

Magento 2: Creating & Running Cron in Custom Module

This article shows how to create and run cronjob in a custom module in Magento 2. To know about general details about setting up and running cron on Magento 2, you may refer to this official documentation. This documentation will show you how you can create cron job on web server as well.

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 YourNamespace_YourModule (app/code/YourNamespace/YourModule). To define the cron settings for your custom module, you need to write the following code in app/code/YourNamespace/YourModule/etc/crontab.xml.

app/code/YourNamespace/YourModule/etc/crontab.xml

As you can see from above code, we have defined to run the execute method of class Test (app/code/YourNamespace/YourModule/Cron/Test.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/YourNamespace/YourModule/Cron/Test.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:

Run cron jobs of a particular group only

There are two group names/ids by default in Magento. They are default and index. If you want to add a new group id for your custom module then you have to create a new file app/code/YourCompany/YourModule/etc/cron_groups.xml:

You can check your new cron group in admin panel at:
Stores -> Configuration -> Advanced -> System -> Cron (Scheduled Tasks)

If your group id is named “your_group_name” then to run cron jobs for that group only, you will have to run the following command:

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.
Thanks.

Magento 2

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed