Running cron jobs in Magento 2

When it comes to Magento 2 and cron jobs, there are some improvements comparing to Magento 1.

It is still abstract in the way that you don’t really run jobs directly, instead, you use cron syntax to setup periodical method execution via Magento scheduler that works on top of system’s cron utility.

Here are some useful hints to help you get started with setting up your own.

Database doesn’t seem to be changed when we compare it with Magento 1 but configuration does.
Magento 2 will execute entries from cron_schedule table just like in Magento 1.

News in configuration is that now we are able to group our jobs and chose if we want our jobs to be executed in parallel as separate processes which could come very handy sometimes.
magento2-cron-configuration

So, in order to run scheduled tasks in Magento, first we need to make sure that we configure the following jobs to run via system cron. This is most simple way to do it:

*/1 * * * * /path/to/php /path/to/m2/installation/bin/magento cron:run [>> /log/file &]
*/1 * * * * /path/to/php /path/to/m2/installation/update/cron.php [>> /log/file &]
*/1 * * * * /path/to/php /path/to/m2/installation/bin/magento setup:cron:run [>> /log/file &

At this point you have all those M2 default jobs ready to go!

So, how to make your own job?

More or less, this is done in the similar way as in Magento 1.
First you need crontab.xml inside your custom module:

<?xml version="1.0"?>
<config xmlns_xsi="http://www.w3.org/2001/XMLSchema-instance" xsi_noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default"> <!-- Doesn't need to be unique -->
        <job name="cron_example" instance="InchooCronExampleCronExample" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

Configuration above is to make sure that every minute, InchooCronExampleCronExample:execute() is run which would (according the code below log it’s name every minute.)

<?php
namespace InchooCronExampleCron;
class Example {
 
    protected $_logger;
 
    public function __construct(PsrLogLoggerInterface $logger) {
        $this->_logger = $logger;
    }
 
    public function execute() {
        $this->_logger->info(__METHOD__);
        return $this;
    }
}

It is also worth mentioning that you could chose to run only one job group at the time.
Here is how you do it:

magento cron:run [--group="cron_group_name"]

Your thoughts appreciated

I hope this helps you with your cron jobs setup – how would you go about this and do you have some tips and tricks to share?

We would be glad to offer you some extra help, we can offer you a detailed custom report based on our technical audit – feel free to get in touch and see what we can do for you!