I am working on a custom module for Magento 2. I did setup crontab there and it is working good with static schedule.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../app/code/Magento/Cron/etc/crontab.xsd">
<group id="default">
<job name="tm-feed-job" instance="TM\Feed\Model\Cron" method="export">
<schedule>* * * * * *</schedule>
</job>
</group>
</config>
But I need the <schedule>* * * * * *</schedule>
dynamic from my database saved value. Here I need to use 3 schedule Daily
Weekly
Monthly
Frequency already saved in database
How can i add dynamic schedule there?
Best Answer
Not as easy as I expected.
First you need to update your
crontab.xml
to setup the config path to your frequency:Now you need to add a field to the configuration to be able to choose the frequency so in
adminhtml/system.xml
:Now we need to create
Vendor\Module\Model\Config\Backend\Frequency
for the frequency backend model:This code looks tricky at first sight but it basically generates the
crontab/default/jobs/tm_feed_job/schedule/cron_expr
config path based on what you've chosen in the frequency dropdown.Interesting side note finding: this is implemented for a couple of modules in M2 natively which includes currency, product alerts, backups, sitemaps. The interesting thing is where the backend model are defined for some of those modules:
Magento\Cron\Model\Config\Backend\Product\Alert
Magento\Cron\Model\Config\Backend\Sitemap
So yeah you read it right. Instead of being in their corresponding module folder, those backend models are located under the
Magento\Cron
module folder.