🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How to Dynamically Schedule Cron Job in Magento 2 System Configuration

By Sanjay JethvaUpdated on Jun 05, 2025 3 min read

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:

How to Dynamically Schedule Cron Job in Magento 2 System Configuration

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

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

2. 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();
    }
}

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

4. Use the below code in your php file at Vendor\Extension\Cron

<?php

namespace Vendor\Extension\Cron;

class CronFile
{
    public function execute()
    {
        // add your custom code as per your requirement
    }
}

That’s it.

Also, please share the solution with Magento community via social media.

Thank you!

Sanjay Jethva Full Image
Article bySanjay 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.