Magento2 – Cron – Module Development Series – Part6

In this blog post, we will see how to setup cron for your modules

Cron is used for recurring tasks for your module. To setup crontab in your module create a crontab.xml file

<?xml version="1.0"?>

<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">  <!-- this can be anything -->
        <job name="excellence_hello_test_cron" instance="Excellence\Hello\Cron\Test" method="execute">
            <schedule>*/5 * * * *</schedule>

and in the class add this code

    namespace Excellence\Hello\Cron;
    use \Psr\Log\LoggerInterface;

    class Test
        protected $logger;

	    public function __construct(LoggerInterface $logger)
	        $this->logger = $logger;

	    public function execute()
	        $this->logger->info('Cron Works');

The code is quite simple and almost similar to magento1

The command to run cron is

php bin/magento cron:run

Also if you need to run only a specific group run this command

php bin/magento cron:run [--group="cron_group_name"]