Add a Magento 2 Cron Job

The cron is an important feature of a Magento store on a production environments. Cron tasks that are scheduled at a set date and time are automatically executed, and in Magento this includes Google sitemap generation, newsletters, emails and more. To add a Magento 2 cron job, you must first add a custom module that contains the cron configuration.

As usual, this starts by declaring the module’s registration.php and module.xml files.

// app/code/[Vendor]/[Module]/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    '[Vendor]_[Module]',
    __DIR__
);
// app/code/[Vendor]/[Module]/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="[Vendor]_[Module]" setup_version="1.0.0" />
</config>

After adding these two files, enable the module and upgrade your database by running the following command line interface commands.

$ /path/to/your/php bin/magento module:enable [Vendor]_[Module] --clear-static-content

$ /path/to/your/php bin/magento setup:upgrade

In Magento 2, the cron configuration is contained within a crontab.xml file. Within this file, add a cron task by defining a job name, a job instance which will tell Magento what class to use to execute the cron task, and a job method which will be the method of the class that contains the functionality.

// app/code/[Vendor]/[Module]/etc/crontab.xml

<?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">
        <job name="clear_order_data" instance="[Vendor]\[Module]\Cron\ClearOrderData" method="execute">
            <schedule>1 * * * *</schedule>
        </job>
    </group>
</config>

Within the <job> nodes, the <schedule> allows you to configure the frequency of the cron task using the default cron format.

The group id specifies the cron group in which the task belongs. By default, Magento provides four.

  • default – which contains most cron jobs
  • index – which refreshes indexers
  • staging – which runs Staging-related tasks (EE only).
  • catalog_event – which runs tasks for target and shopping cart rules (EE only).

In this example, a clear_order_data job has been defined, and as such, a ClearOrderData class will be responsible for executing some functionality that will delete orders (on a staging website!).

The file might look similar to the below.

// app/code/[Vendor]/[Module]/Cron/ClearOrderData.php

<?php
namespace [Vendor]\[Module]\Cron;

use Magento\Framework\Registry;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;

class ClearOrderData
{
    /**
     * @var Registry
     */
    protected $registry;

    /**
     * @var CollectionFactory
     */
    protected $orderCollectionFactory;

    /**
     * ClearCollectionData constructor.
     *
     * @param Registry $registry
     * @param CollectionFactory $orderCollectionFactory
     */
    public function __construct(
        Registry $registry,
        CollectionFactory $orderCollectionFactory
    ) {
        $this->registry = $registry;
        $this->orderCollectionFactory = $orderCollectionFactory;
    }

    /**
     * Clear order data
     *
     * @return void
     */
    public function execute()
    {
        $this->registry->register('isSecureArea', 'true');
        $orders = $this->orderCollectionFactory->create();
        foreach ($orders as $order) {
            $order->delete();
        }
        $this->registry->unregister('isSecureArea');
    }
}

In order for the cron task to run at the time scheduled in crontab.xml, ensure that you have configured cron correctly on your server environment that the Magento application sits on.

You can also periodically check the cron_schedule database table and see if it gets populated with the defined scheduled tasks.

Note: This article is based on Magento Open Source version 2.1.8.