Skip to content

How do you create a custom cron job in Magento 2 and ensure it executes only once per cycle?

Here crontab.xml file

<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="vendor_module_cronjob" instance="VendorModuleCronCustomJob" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

Here CustomJob.php file

<?php
namespace VendorModuleCron;

use PsrLogLoggerInterface;

class CustomJob
{
    protected $logger;

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

    public function execute()
    {
        // Job logic here
        $this->logger->info("Cron job executed.");
    }
}