Magento 2 Magento 2 Tutorials

How to Dynamically Schedule CRON Job in Magento 2?

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
Loading...Loading...
How to Dynamically Schedule CRON Job in Magento 2

The CRON job feature that Magento 2 brings in, lets the store owner schedule particular activities to be executed at a particular time. With the help of CRON job, the store owners can set a specific time in order to carry out any particular task to carry out automatically according to their requirements. 

The store owner needs an additional CRON job that can work in the custom modules for certain particular features such as newsletter, backup scheduling, Google Sitemaps, etc.

For example, you built a module that works on the backup of your store. During this type of scenario, it is difficult to configure/run backups manually anytime you require. This will be an issue when you require backup of your whole store on the basis of the opening hours of your store. Wondering if the time and backup of the store manually?

The manual process is highly time-consuming. To do it the right way, one can utilize a quick way to dynamically schedule the CRON job in the Magento 2 Configuration.

Add options on the system configuration that asks for frequency to run a CRON job as shown below:

Schedule Cron Job Magento 2

Here is the code to help the store owners dynamically schedule CRON job in Magento 2. Follow the below-mentioned step by step process:

Method to Dynamically Schedule Cron Job in Magento 2 System Configuration

Add the below code in the system.xml file at Vendor/Extension/etc/adminhtml

<group id="cronScheduled" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1"
 showInStore="1">
 <label>Backup Scheduled</label>
 <field id="frequency" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1"
 showInStore="1">
 <label>Frequency</label>
 <source_model>Magento\Cron\Model\Config\Source\Frequency</source_model>
 <backend_model>Vendor\Extension\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>

Use the below code in the CronConfig.php at Vendor/Extension/Model/Config/

<?php
namespace Vendor\Extension\Model\Config;
class CronConfig extends \Magento\Framework\App\Config\Value
{
 const CRON_STRING_PATH = 'crontab/default/jobs/vendor_extension_cron_job/schedule/cron_expr';
const CRON_MODEL_PATH = 'crontab/default/jobs/vendor_extension_cron_job/run/model';
protected $_configValueFactory;
protected $_runModelPath = '';
public function __construct(
 \Magento\Framework\Model\Context $context,
 \Magento\Framework\Registry $registry,
 \Magento\Framework\App\Config\ScopeConfigInterface $config,
 \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
 \Magento\Framework\App\Config\ValueFactory $configValueFactory,
 \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
 \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
 $runModelPath = '',
 array $data = []
 )
 {
 $this->_runModelPath = $runModelPath;
 $this->_configValueFactory = $configValueFactory;
 parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
 }

 public function afterSave()
 {
 $time = $this->getData('groups/cronScheduled/fields/time/value');
 $frequency = $this->getData('groups/cronScheduled/fields/frequency/value');
$cronExprArray = [
 intval($time[1]),
 intval($time[0]),
 $frequency == \Magento\Cron\Model\Config\Source\Frequency::CRON_MONTHLY ? '1' : '*',
 '*',
 $frequency == \Magento\Cron\Model\Config\Source\Frequency::CRON_WEEKLY ? '1' : '*',
 ];
$cronExprString = join(' ', $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(__('We can\'t save the cron expression.'));
 }
return parent::afterSave();
 }
}

In the crontab.xml file at Vendor/Extension/etc, use the below code:

<?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="vendor_extension_cron_job" instance="Vendor\Extension\Cron\CronFile" method="execute">
 <config_path>
 crontab/default/jobs/vendor_extension_cron_job/schedule/cron_expr
 </config_path>
 </job>
 </group>
</config>
  • Use the below code in the CronConfig.php at Vendor/Extension/Model/Config/
<?php
namespace Vendor\Extension\Cron;
class CronFile
{
 public function execute()
 {
 // add your custom code as per your requirement
 }
}

Hope this tutorial has been helpful for scheduling the CRON job on your Magento 2 store, if you face any issues while implementing the process, feel free to reach us out.

You may also like
What is SaaS?
What is SaaS? Top 5 World Best SaaS B2B companies?
Boost Traffic and Visibility in 2021 using the SEO Tips
Boost Traffic and Visibility in 2021 using the SEO Tips

Leave Your Comment

Your Comment*

Your Name*