Featured image of post How to add custom cron tasks

How to add custom cron tasks

The instruction how to add custom cron tasks in your module

Introduction

Cron command list

Magento has provided CLI commands to work with cron tasks since version 2.2.0

  • cron:install - generates and installs crontab for a current user and a current instance
  • cron:remove - removes tasks from crontab

An example of what contains crontab after running cron:install:

1
2
3
4
5
#~ MAGENTO START c843c167b6a41dfbd235a8330f6fd4b6
* * * * * /bin/php /var/www/bin/magento cron:run 2>&1 | grep -v "Ran jobs by schedule" >> /var/www/var/log/magento.cron.log
* * * * * /bin/php /var/www/update/cron.php >> /var/www/var/log/update.cron.log
* * * * * /bin/php /var/www/bin/magento setup:cron:run >> /var/www/var/log/setup.cron.log
#~ MAGENTO END c843c167b6a41dfbd235a8330f6fd4b6

How to add your own cron tasks

There is more information about these commands in this documentation: Create the Magento crontab

The tasks that you see above are the default cron tasks of Magento.
If you need you can add own cron tasks in your module.
It’s very easy to do. You just need to add the following configuration to your di.xml file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<type name="Magento\Framework\Crontab\TasksProviderInterface">
    <arguments>
        <argument name="tasks" xsi:type="array">
            <item name="yourCommand" xsi:type="array">
                <item name="command" xsi:type="string">{magentoRoot}bin/magento your:command >> {magentoLog}your.log</item>
            </item>
            <item name="yourScript" xsi:type="array">
                <item name="command" xsi:type="string">{magentoRoot}path/to/your/script.php >> {magentoLog}your.log</item>
            </item>
        </argument>
    </arguments>
</type>

{magentoRoot} and {magentoLog} are placeholders and will be replaced on the paths to the root directory of Magento and the directory with Magento logs.
With this configuration, the command cron:install will generate crontab with your tasks as in the following example:

1
2
3
4
5
6
7
#~ MAGENTO START c843c167b6a41dfbd235a8330f6fd4b6
* * * * * /bin/php /var/www/bin/magento cron:run 2>&1 | grep -v "Ran jobs by schedule" >> /var/www/var/log/magento.cron.log
* * * * * /bin/php /var/www/update/cron.php >> /var/www/var/log/update.cron.log
* * * * * /bin/php /var/www/bin/magento setup:cron:run >> /var/www/var/log/setup.cron.log
* * * * * /bin/php /var/www/bin/magento your:command >> /var/www/var/log/your.log
* * * * * /bin/php /var/www/path/to/your/script.php >> /var/www/var/log/your.log
#~ MAGENTO END c843c167b6a41dfbd235a8330f6fd4b6

That’s all πŸ˜‰

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy