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:

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

  2. Use the below code in the CronConfig.php at Vendor/Extension/Model/Config/

  3. In the crontab.xml file at Vendor/Extension/etc, use the below code:
  4. Use the below code in your php file at Vendor\Extension\Cron

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:

5
(based on 9 Reviews)
How to Dynamically Schedule Cron Job in Magento 2 System Configuration

Dipak Vadher

Dipak is a Magento Developer at Meetanshi. Apart from work, he loves playing cricket with his friends. Traveling and exploring new places is something that he is passionate about.

Leave a Reply

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