{"id":1809,"date":"2021-06-30T09:27:27","date_gmt":"2021-06-30T09:27:27","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/dynamically-schedule-cron-job-in-magento-2-system-configuration\/"},"modified":"2025-07-16T17:38:15","modified_gmt":"2025-07-16T12:08:15","slug":"dynamically-schedule-cron-job-in-magento-2-system-configuration","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/dynamically-schedule-cron-job-in-magento-2-system-configuration\/","title":{"rendered":"How to Dynamically Schedule Cron Job in Magento 2 System Configuration"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The cron job feature provided by\u00a0Magento 2\u00a0allows 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For instance, you\u2019ve 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?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No, it is time-consuming. Right? In that case, use a quick way to&nbsp;dynamically schedule cron job in Magento 2 system configuration!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Add options on the system configuration that asks for frequency to run a cron job as shown below:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/meetanshi.com\/blog\/wp-content\/uploads\/2021\/06\/Screenshot-at-May-13th-2021-10.23.56-am-1024x437.png\" alt=\"How to Dynamically Schedule Cron Job in Magento 2 System Configuration\" class=\"wp-image-15205\"\/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">Check out the below code and use a quick way to schedule your activity.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Method to Dynamically Schedule Cron Job in Magento 2 System Configuration<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">1. Add the below code in the&nbsp;<strong>system.xml<\/strong>&nbsp;file at&nbsp;<strong>Vendor\/Extension\/etc\/adminhtml<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;group id=\"cronScheduled\" translate=\"label\" type=\"text\" sortOrder=\"20\" showInDefault=\"1\" showInWebsite=\"1\"\n       showInStore=\"1\">\n    &lt;label>Backup Scheduled&lt;\/label>\n    &lt;field id=\"frequency\" translate=\"label\" type=\"select\" sortOrder=\"1\" showInDefault=\"1\" showInWebsite=\"1\"\n           showInStore=\"1\">\n        &lt;label>Frequency&lt;\/label>\n        &lt;source_model>Magento\\Cron\\Model\\Config\\Source\\Frequency&lt;\/source_model>\n        &lt;backend_model>Vendor\\Extension\\Model\\Config\\CronConfig&lt;\/backend_model>\n    &lt;\/field>\n    &lt;field id=\"time\" translate=\"label comment\" sortOrder=\"2\" type=\"time\" showInDefault=\"1\" showInWebsite=\"1\"\n           showInStore=\"1\">\n        &lt;label>Start Time&lt;\/label>\n    &lt;\/field>\n&lt;\/group><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">2. Use the below code in the&nbsp;<strong>CronConfig.php<\/strong>&nbsp;at&nbsp;<strong><strong>Vendor\/Extension\/Model\/Config\/<\/strong><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n\nnamespace Vendor\\Extension\\Model\\Config;\n\nclass CronConfig extends \\Magento\\Framework\\App\\Config\\Value\n{\n    const CRON_STRING_PATH = 'crontab\/default\/jobs\/vendor_extension_cron_job\/schedule\/cron_expr';\n\n    const CRON_MODEL_PATH = 'crontab\/default\/jobs\/vendor_extension_cron_job\/run\/model';\n\n    protected $_configValueFactory;\n\n    protected $_runModelPath = '';\n\n    public function __construct(\n        \\Magento\\Framework\\Model\\Context $context,\n        \\Magento\\Framework\\Registry $registry,\n        \\Magento\\Framework\\App\\Config\\ScopeConfigInterface $config,\n        \\Magento\\Framework\\App\\Cache\\TypeListInterface $cacheTypeList,\n        \\Magento\\Framework\\App\\Config\\ValueFactory $configValueFactory,\n        \\Magento\\Framework\\Model\\ResourceModel\\AbstractResource $resource = null,\n        \\Magento\\Framework\\Data\\Collection\\AbstractDb $resourceCollection = null,\n        $runModelPath = '',\n        array $data = []\n    )\n    {\n        $this->_runModelPath = $runModelPath;\n        $this->_configValueFactory = $configValueFactory;\n        parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);\n    }\n\n\n    public function afterSave()\n    {\n        $time = $this->getData('groups\/cronScheduled\/fields\/time\/value');\n        $frequency = $this->getData('groups\/cronScheduled\/fields\/frequency\/value');\n\n        $cronExprArray = [\n            intval($time[1]),\n            intval($time[0]),\n            $frequency == \\Magento\\Cron\\Model\\Config\\Source\\Frequency::CRON_MONTHLY ? '1' : '*',\n            '*',\n            $frequency == \\Magento\\Cron\\Model\\Config\\Source\\Frequency::CRON_WEEKLY ? '1' : '*',\n        ];\n\n        $cronExprString = join(' ', $cronExprArray);\n\n        try {\n            $this->_configValueFactory->create()->load(\n                self::CRON_STRING_PATH,\n                'path'\n            )->setValue(\n                $cronExprString\n            )->setPath(\n                self::CRON_STRING_PATH\n            )->save();\n            $this->_configValueFactory->create()->load(\n                self::CRON_MODEL_PATH,\n                'path'\n            )->setValue(\n                $this->_runModelPath\n            )->setPath(\n                self::CRON_MODEL_PATH\n            )->save();\n        } catch (\\Exception $e) {\n            throw new \\Exception(__('We can\\'t save the cron expression.'));\n        }\n\n        return parent::afterSave();\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">3. In the&nbsp;<strong>crontab.xml<\/strong>&nbsp;file at&nbsp;<strong>Vendor\/Extension\/etc<\/strong>, use the below code:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?xml version=\"1.0\"?>\n&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n        xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Cron:etc\/crontab.xsd\">\n    &lt;group id=\"default\">\n        &lt;job name=\"vendor_extension_cron_job\" instance=\"Vendor\\Extension\\Cron\\CronFile\" method=\"execute\">\n            &lt;config_path>\n                crontab\/default\/jobs\/vendor_extension_cron_job\/schedule\/cron_expr\n            &lt;\/config_path>\n        &lt;\/job>\n    &lt;\/group>\n&lt;\/config><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">4. Use the below code in your php file at&nbsp;<strong><strong>Vendor\\Extension\\Cron<\/strong><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n\nnamespace Vendor\\Extension\\Cron;\n\nclass CronFile\n{\n    public function execute()\n    {\n        \/\/ add your custom code as per your requirement\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">That\u2019s it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Also, please share the solution with Magento community via social media.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thank you!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The cron job feature provided by\u00a0Magento 2\u00a0allows 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 [&hellip;]<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[34],"tags":[],"class_list":["post-1809","post","type-post","status-publish","format-standard","hentry","category-magento"],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1809","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=1809"}],"version-history":[{"count":7,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1809\/revisions"}],"predecessor-version":[{"id":18040,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1809\/revisions\/18040"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=1809"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=1809"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=1809"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}