Magento2 How To Create a Custom Cron

We can create a custom cron in Magento2 using following custom module extension and can use it for our custom requirements.

Let's create a custom cron with following steps defined.

Step 1: We need to create an module.xml in app/code/Magemeta/Custom/etc/module.xml to register our custom module.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Magemeta_Custom" setup_version="1.0.0"/>
</config>

Step 2: We need to create a di.xml in app/code/Magemeta/Custom/etc/di.xml to register our custom cron in the Magento system with schdule defined in the same 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="test_group">
        <job instance="Magemeta\Custom\Cron\Test" method="execute" name="test_cron">
            <schedule>0 * * * *</schedule> <!-- Define as per your need -->
        </job>
    </group>
</config>

Step 3: We need to create an Test.php in app/code/Magemeta/Custom/Cron/Test.php to register our custom cron class.

<?php
namespace Magemeta\Custom\Cron;
class Test {
    /**
    * @return mixed
    */
    public function execute()
    {
        mail('loremipsum@loremipsum.com','Test Subject', 'Test Message Content');
    }
}

And this is our custom cron we have created using small module extension. Cheers! Hope this helps you guys!

 

Leave a Reply