How to Create Cron Job Programmatically in Magento 2

The cron Job will create a command or a script that is appropriate with the task you want to do. Instead of manual working, the Cron Job allows running automatically in exact time and date. Due to its automation, the Cron Jobs is the perfect choice for repeated projects every date or every week.

Please follow the guides to start the cron job program as your wish:

How to Create Cron Job in Magento 2
  • Create a class within the “Cron” folder
  • Manually setup the cron schedule by using PHP: bin/magento cron:run
  • Find a log in the var/log/system.log after the cron job has run.
  • Login to Magento 2 Admin panel, do as the path: Stores > Configuration > Advanced > System, then change scheduler settings per cron group.
  • Finally, run cron from the command line:

magento cron:run [--group="<cron group name>"]

Create crontab.xml
File: app/code/JJ/Test/etc/crontab.xml

Content would be
* ** * * *

group id is your cron group name. You can run only cron for single group at a time.
job instance is a class to be instantiated (classpath).
job method is the method in job instance to call.
job name is Unique ID for this cron job.
schedule is the schedule in cron format. The following graph shows what it consists of:

  • * * * * command to be executed
    | | | | |
    | | | | +—– Day of week (0 – 7) (Sunday=0 or 7)
    | | | +——- Month (1 – 12)
    | | +——— Day of month (1 – 31)
    | +———– Hour (0 – 23)
    +————- Minute (0 – 59)

In crontab.xml, we have defined job instance as JJ\Test\Cron\Test. It should be created now.

Test.php

<?php

namespace JJ\Test\Cron;

class Test
{

	public function execute()
	{

		$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/cron.log');
		$logger = new \Zend\Log\Logger();
		$logger->addWriter($writer);
		$logger->info(__METHOD__);

		return $this;

	}
}

Leave a comment

Your email address will not be published. Required fields are marked *