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
<?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="iyngaran_cron_demo"
instance="Iyngaran\DemoModule\Cron\Demo"
method="execute">
<schedule>*/15 * * * *</schedule><!-- run 15th minutes -->
</job>
</group>
</config>
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:
<config>
<group id="<group_name>">
<job name="<job_name>" instance="<classpath>" method="<method>">
<schedule><time></schedule>
</job>
</group>
</config>
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
<?php
namespace Iyngaran\DemoModule\Cron;
class Demo {
protected $_logger;
public function __construct(\Psr\Log\LoggerInterface $logger) {
$this->_logger = $logger;
}
/**
* Method executed when cron runs in server
*/
public function execute() {
$this->_logger->debug("Running Cron from Iyngaran's demo class");
return $this;
}
}
You can manually run cron from terminal/command line with the following command:
Run all cron jobs
sudo php bin/magento cron:run
If it doesn’t work (doesn’t create any entries in cron_schedule table) then try flushing cache first:
sudo php bin/magento cache:flush
sudo php bin/magento cron:run
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.