How to Create Cron Job Programmatically in Magento 2

Magento Cron job is one of the essential features in Magento 2. It supports to configure commands or script that systematically runs and performs the tasks you intend it to. With the cron job, you don't need to manually reindex.

Steps to create CronJob

Create crontab.xml

Directory

app/code/VendorName/ModuleName/etc/crontab.xml

Content for 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 instance="VendorName\ModuleName\Cron\CronJob" method="execute" name="vendorname_modulename_cron">
			<schedule>* * * * *</schedule>
		</job>
	</group>
</config>

Create CronJob.php

Directory

app/code/VendorName/ModuleName/Cron/CronJob.php

Content for CronJob.php

<?php

namespace VendorName\ModuleName\Cron;

class CronJob
{

	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;

	}
}

 

If you are looking for Magento Services, visit Magento Web Agency.