How To Dynamically Schedule Cron Job By Configuration In Magento 2

Hello Everyone,

In this blog, we will learn about how to Dynamically Schedule Cron Job By System Configuration in Magento 2.

Magento 2 store owners can set specific time for some tasks to run automatically.

Tasks include newsletter send, backup etc.

Without wasting your time, let us guide you straight away. Follow the easy step given below to Dynamically Schedule Cron Job By Configuration in Magento 2.

STEPS FOR DYNAMICALLY SCHEDULE CRON JOB BY SYSTEM CONFIGURATION IN MAGENTO 2

Step 1: Create file crontab.xml

app/code/Vendor/Extension/etc/crontab.xml

<?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="Vendor\Extension\Cron\CustomCron" method="execute" name="my_cron_job">

            <config_path>crontab/default/jobs/my_cron_job/schedule/cron_expr</config_path>

        </job>

    </group>

</config>

Step 2: Add/Update system.xml file

app/code/Vendor/Extension/etc/adminhtml/system.xml

<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>

Step 3: Create file Cronconfig.php

app/code/Vendor/Extension/Model/Config/Cronconfig.php

<?php

namespace Vendor\Extension\Model\Config;

class Cronconfig extends \Magento\Framework\App\Config\Value

{

    const CRON_STRING_PATH = 'crontab/default/jobs/my_cron_job/schedule/cron_expr';

    const CRON_MODEL_PATH = 'crontab/default/jobs/my_cron_job/run/model';

     /**

     * @var \Magento\Framework\App\Config\ValueFactory

     */

    protected $_configValueFactory;

    /**

     * @var mixed|string

     */

    protected $_runModelPath = '';

    /**

     * CronConfig1 constructor.

     * @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|null $resource

     * @param \Magento\Framework\Data\Collection\AbstractDb|null $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);

    }

    /**

     * @return CronConfig1

     * @throws \Exception

     */

    public function afterSave()

    {

        $time = $this->getData('groups/configurable_cron/fields/time/value');

        $frequency = $this->getData('groups/configurable_cron/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(__('Some Thing Want Wrong , We can\'t save the cron expression.'));

        }

        return parent::afterSave();

    }

}

Step 4: Create file CustomCron.php

app/code/Vendor/Extension/Cron/CustomCron.php

<?php

namespace Vendor\Extension\Cron;

class CustomCron

{

    protected $logger;

    /**

    * Constructor

    *

    * @param \Psr\Log\LoggerInterface $logger

    */

    public function __construct(\Psr\Log\LoggerInterface $logger)

    {

        $this->logger = $logger;

    }

    public function execute()

    {   

        $this->logger->info("Magecurious custom cron is executed.");

        //add your custom cron job logic here.

    }

}

Step 5: Finally run the below commands

$ php bin/magento cache:clean

$ php bin/magento cache:flush


Step 6: Output:

You can see below system configuration output, change the value as per your requirements. Cron will be run at selected Frequency and Set Time.

Final Thoughts:

So this was the easiest way which we have told you in this blog. This is how you can Add Inline Edit Functionality in UI Grid Backend in Magento 2. Hope you liked the blog.

So quickly go to the comment box and tell me how you like this blog?

Stay tuned with us on our site to get new updates of Magento.

Thanks for reading and visiting our site.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Leave a Reply

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