Reading list Switch to dark mode

    Magento2 Setup Cron By Config Path

    Updated 23 February 2024

    Setup Cron By using Config Path, So we can schedule cron dynamically.

    Here we learn, how to setup cron by using config path.
    Let’s Start.

    1. Create crontab.xml file inside app/code/Webkul/CronSetup/etc directory.

    <?xml version="1.0"?>
    <!-- 
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @package   Webkul_CronSetup
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
     -->
    <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="my_cron_setup_job" instance="Webkul\CronSetup\Cron\CronFile" method="execute">
                <config_path>crontab/default/jobs/my_cron_setup_job/schedule/cron_expr</config_path>
            </job>
        </group>
    </config>

    2. Now open system.xml file and add new group in that.
    #File: app/code/Webkul/CronSetup/etc/adminhtml/system.xml

    <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>Webkul\CronSetup\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>

    3. Now create CronConfig.php file which we have given in system.xml file.
    # File: Webkul/CronSetup/Model/Config/CronConfig.php

    <?php
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @package   Webkul_CronSetup
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
    
    namespace Webkul\CronSetup\Model\Config;
    
    class CronConfig extends \Magento\Framework\App\Config\Value
    {
        /**
         * Cron string path constant
         */
        const CRON_STRING_PATH = 'crontab/default/jobs/my_cron_setup_job/schedule/cron_expr';
    
        /**
         * Cron model path constant
         */
        const CRON_MODEL_PATH = 'crontab/default/jobs/my_cron_setup_job/run/model';
    
        /**
         * @var \Magento\Framework\App\Config\ValueFactory
         */
        protected $_configValueFactory;
    
        /**
         * @var string
         */
        protected $_runModelPath = '';
    
        /**
         * @param \Magento\Framework\Model\Context $context
         * @param \Magento\Framework\Registry $registry
         * @param \Magento\Framework\App\Config\ScopeConfigInterface $config
         * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
         * @param \Magento\Framework\App\Config\ValueFactory $configValueFactory
         * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
         * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
         * @param string $runModelPath
         * @param array $data
         */
        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);
        }
    
        /**
         * @inheritdoc
         *
         * @return $this
         * @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], //Minute
                (int) $time[0], //Hour
                $frequency == \Magento\Cron\Model\Config\Source\Frequency::CRON_MONTHLY ? '1' : '*', //Day of the Month
                '*', //Month of the Year
                $frequency == \Magento\Cron\Model\Config\Source\Frequency::CRON_WEEKLY ? '1' : '*', //Day of the Week
            ];
    
            $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();
        }
    }

    CronConfig class insert the fake entry in core_config_data table, that we have used in crontab.xml

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    4. Finally Create CronFile.php file

    <?php
    /**
     * @category  Webkul
     * @package   Webkul_CronSetup
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
    namespace Webkul\CronSetup\Cron;
    
    /**
     * custom cron actions
     */
    class CronFile
    {
        public function execute()
        {
            // do your custom code as your requirement
        }
    }

    Now check in Admin Store Configuration you will see the cron setting as:

    cronsetting

    Thanks.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    5 comments

  • bilal younas
    • Zeba Hakim (Moderator)
  • Abid H. Malik
  • andreimam
    • Suraj Kumar
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home