Magento2 – How to Set Up and Manage Cron Jobs

magento2

My objective is to execute a custom class/method (e.g. send data to a backend system) every X minutes. Seems cron is the way to go. Though, I'm new to cron in Magento 2.

What I see so far is I should create a etc\crontab.xml file

<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="mymodule_orders_job" instance="My\Module\Model\Observer" >
<schedule>*/5 * * * *</schedule>
</job>
</group>
</config>

and "Observer" does the work. Seems simple enough.

What I'm confused on is, how does this get into cron (crontab)? Also, I see there's a cron_schedule table…not sure what that's used for.

Finally, I want the flexibility to 1) enabled/disabled the job in a custom Admin config and 2) set the interval on the same custom Admin.

I suspect for the custom Admin it would create the etc\crontab.xml and set parms accordingly? Also, since this is a packaged module need the module to be able set things up inclusively

Best Answer

You need setup not only a cron job execution schedule in a Magento 2 extension, but also setup a generic cron job execution schedule in an operating system.

The operating system will run Magento 2 by the schedule, and Magento 2 will check it's internal schedule and run the appropriate extensions jobs.

The generic operating system schedule should run Magento 2 more frequent then any of internal Magento 2 schedules. I recommend run Magento 2 every 5-10-15 minutes, depends on your server performance.

Related Topic