How to Dynamically Schedule Cron Job in Magento 2 System Configuration
The cron job feature provided by Magento 2 allows scheduling activities to be executed at a particular time. Magento 2 store owners can set a specific time for carrying out such automated tasks according to their requirements.
However, the store owner needs an additional cron job that can work in the custom modules as certain custom features like a newsletter, backup scheduling, google sitemaps, etc require a cron job.
For instance, you’ve created a module that works on backup your store. In such a scenario, it is troublesome to configure or run the backup manually whenever you need. What if you require to backup your whole store based on the hours? Is it possible to wait for a determined time and backup the store manually?
No, it is time-consuming. Right? In that case, use a quick way to dynamically schedule cron job in Magento 2 system configuration!
Add options on the system configuration that asks for frequency to run a cron job as shown below:
Check out the below code and use a quick way to schedule your activity.
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
1234567891011121314<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/
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071<?phpnamespace 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:
1234567891011<?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 your php file at Vendor\Extension\Cron
1234567891011<?phpnamespace Vendor\Extension\Cron;class CronFile{public function execute(){// add your custom code as per your requirement}}
That’s it.
Any doubts? Do mention them in the Comments section below.
I would be glad to help you out.
Also, please share the solution with Magento Community via social media.
Thank you.
Related Posts:
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
Hi,
Tutorial was nice. Just would like to know in cron_schedule table “schedule_at” field is always blank. If we set time suppose 2:30 and current time 2:00. Then it shouldn’t show entry in the table that this cron will run on 2:30. It’s always null value.
Could you please give me the reason, why it is always null
Hello Bhavin,
You will need to be confirmed that the cron is set up and working properly.
You can check the same from ssh/terminal or var/log/ cron logs.
Thank You