We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
- Home
- Blog
- eCommerce Talk
- How To Set up Custom Cron Job in Magento 2
How To Set up Custom Cron Job in Magento 2
Setup Cron job by configuration allows you to schedule Cron dynamically. In a few cases, developers make use of static time expressions to set Cron Job in a custom module. In that case, whenever you make any changes to the time expression, you must have to change the crontab.xml file.
In order to avoid this issue, we have come up with programmatic solutions by which you can quickly make any changes to the time expression. In case you missed our previous article on How to change Magento 2 configuration using Command Line Interface, check it out here.
If you follow the steps below from the admin configuration, you can easily make any changes to the time expression. Therefore, you don’t need to make the changes to the crontab.xml file.
Let’s get started on how to set up Custom Cron Job by configuration in Magento 2.
Steps to set up Custom Cron Job in Magento 2:
- Step 1: Create crontab.xml file
First of all, you need to go to the path:
app\code\MageSpark\Crontime\etc\crontab.xml
And add the contents in crontab.xml file.
<?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="MageSpark\Crontime\Cron\Cronfile" method="execute" name="my_cron_job"> <config_path>crontab/default/jobs/my_cron_job/schedule/cron_expr</config_path> </job> </group> </config>
- Step 2: Create system.xml file for CRON configuration
Now, go to the path:
app\code\MageSpark\Crontime\etc\adminhtml\system.xml,
and add a new group to the system.xml file.
<group id="configurable_cron" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="0"> <label>Cron Settings</label> <field id="frequency" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0"> <label>Frequency</label> <source_model>Magento\Cron\Model\Config\Source\Frequency</source_model> <backend_model>MageSpark\Crontime\Model\Config\Cronconfig</backend_model> </field> <field id="time" translate="label comment" sortOrder="2" type="time" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Start Time</label> </field> </group>
- Step 3: Create Cronconfig.php file
Then, got to the path:
app\code\MageSpark\Crontime\Model\Config\Cronconfig.php,
and add Cronconfig.php file.
<?php namespace MageSpark\Crontime\Model\Config; use Magento\Cron\Model\Config\Source\Frequency; use Magento\Framework\App\Cache\TypeListInterface; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Config\Value; use Magento\Framework\App\Config\ValueFactory; use Magento\Framework\Data\Collection\AbstractDb; use Magento\Framework\Model\Context; use Magento\Framework\Model\ResourceModel\AbstractResource; use Magento\Framework\Registry; class Cronconfig extends Value { public const CRON_STRING_PATH = 'crontab/default/jobs/my_cron_job/schedule/cron_expr'; public const CRON_MODEL_PATH = 'crontab/default/jobs/my_cron_job/run/model'; /** * @var ValueFactory */ protected $_configValueFactory; /** * @var mixed|string */ protected $_runModelPath = ''; /** * CronConfig constructor. * * @param Context $context * @param Registry $registry * @param ScopeConfigInterface $config * @param TypeListInterface $cacheTypeList * @param ValueFactory $configValueFactory * @param AbstractResource|null $resource * @param AbstractDb|null $resourceCollection * @param string $runModelPath * @param array $data */ public function __construct( Context $context, Registry $registry, ScopeConfigInterface $config, TypeListInterface $cacheTypeList, ValueFactory $configValueFactory, AbstractResource $resource = null, AbstractDb $resourceCollection = null, $runModelPath = '', array $data = [] ) { $this->_runModelPath = $runModelPath; $this->_configValueFactory = $configValueFactory; parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); } /** * @return CronConfig * @throws \Exception */ public function afterSave() { $time = $this->getData('groups/configurable_cron/fields/time/value'); $frequency = $this->getData('groups/configurable_cron/fields/frequency/value'); $cronExprArray = [ (int)$time[1], (int)$time[0], $frequency == Frequency::CRON_MONTHLY ? '1' : '*', '*', $frequency == Frequency::CRON_WEEKLY ? '1' : '*', ]; $cronExprString = implode(' ', $cronExprArray); try { $this->_configValueFactory->create()->load( self::CRON_STRING_PATH, 'path' )->setValue( $cronExprString )->setPath( self::CRON_STRING_PATH )->save(); $this->_configValueFactory->create()->load( self::CRON_MODEL_PATH, 'path' )->setValue( $this->_runModelPath )->setPath( self::CRON_MODEL_PATH )->save(); } catch (\Exception $e) { throw new \Exception(__('Some Thing Want Wrong , We can\'t save the cron expression.')); } return parent::afterSave(); } }
- Step 4: Now, you can add Cronfile.php in the path below:
app\code\MageSpark\Crontime\Cron\Cronfile.php
<?php namespace MageSpark\Crontime\Cron; class Cronfile { public function execute() { //Add your cron executed code here. } }
Therefore, following all the above steps, you can quickly set up and configure Cron job in Magento 2. If you have any queries or face any problems, feel free to mention them in the comment section below. We would be glad to help with this.
Don't forget to share this solution with your Magento community or friends over social media and stay connected with us to get more Magento 2 tech guides.
Happy coding!!