Today we going to create a custom cronjob module in Magento 2.x
Cronjob is run automatically on the server, based on a specific time. If we require to run some code frequently then need to create cron job for that code. Cronjob runs your code as given your scheduled time. Magento also supports cronjob. This blog for creating a custom cronjob in Magento 2.x
Let’s start by creating a cronjob module.
Step1. Create module directory
Go to Magento app/code directory and create a directory with your vendor name. My vendor name is “CoolCodders”.
After creating the vendor directory, need to create a directory for the module. My module name is “Cronjob”.
My custom module directory path is like “MAGENTO_ROOT/app/code/CoolCodders/Cronjob”
Step2. Create module registration file
<?php
//file path: MAGENTO_ROOT/app/code/CoolCodders/Cronjob/registration.php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'CoolCodders_Cronjob',
__DIR__
);
Step3. Step3. Create module config file
<?xml version="1.0"?>
<!-- file path: MAGENTO_ROOT/app/code/CoolCodders/Cronjob/etx/module.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="CoolCodders_Cronjob" setup_version="1.0.0" />
</config>
Step4. Create crontab config file
<?xml version="1.0"?>
<!-- file path: MAGENTO_ROOT/app/code/CoolCodders/Cronjob/etx/crontab.xml -->
<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="CoolCodders\Cronjob\Cron\Custom" method="execute" name="cool_cronjob_01">
<schedule>2 * * * *</schedule>
</job>
</group>
</config>
Step5. Create cron logic file
<?php
//file path: MAGENTO_ROOT/app/code/CoolCodders/Cronjob/Cron/Custom.php
namespace CoolCodders\Cronjob\Cron;
class Custom
{
public function execute()
{
/*
*
* Your logic
*
*/
}
}
That’s the steps to create a custom cronjob in Magento 2.x