We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
How to Create a Cron with Config Path

Magento has several cron jobs that are running to execute tasks that are needed. These tasks are configured to be executed repeatedly. Let's see in this post how you can create a cron with system configuration regarding the schedule time.
First of all we will need to declare our cron in the crontab.xml of our module. Only that in this time instead of the schedule node which has a fixed schedule time, we will add the node config_path and the path to the configuration. This configuration path will be saved in the core_config_data table and will have as value the schedule time of the cron which can be configured in the system configuration as we will see below. So in this case the schedule time is dynamic and it can be easily changed in system configuration.
For our post we used again our MageVision Blog Posts system menu in admin to add the configuration we need. The configuration will include if the cron is enabled, the starting time and the frequency. Below you can see the system.xml file we need and the output on system configuration. The most important configuration field is the frequency as it has a custom backend model which we will see it closer a bit more down.

The custom backend model that we used above, is the one that helps us to save the schedule time of the cron in the core_config_data table. The schedule time is consist of the values of both our system fields, time and frequency. The format of the value in the core_config_data table has to be like when we declare a schedule time of a cron manually. For our configuration, the value will be like 0 0 * * *, which means that our cron will run daily at 00:00:00.
Finally below you can have also a look on our execute function that will be executed when our cron will run. There is a check if the cron is enabled and then you can simply add your code.
The full example as extension can be found here.
Feel free to share this post and ask your questions in the comments below.
Till next time!