Blog Post Image
5 October, 2020

Create and test a custom cron job in magento

Icon

Luigi Laezza

During one of my latest Magento projects I had to create custom cron jobs, so I decided to write a small how-to guide, that might help you do the same.

FIRST OFF YOU WILL NEED A NEW CUSTOM BUNDLE.
In app/etc/modules/New_Module.xml

<?xml version="1.0"?>
<config>
    <modules>
        <New_Module>
            <active>true</active>
            <codePool>local</codePool>
        </New_Module>
    </modules>
</config>

In app/code/local/New/Module/etc

<?xml version="1.0"?>
<config>
   <modules>
      <New_Module>
         <version>0.0.1</version>
      </New_Module>
   </modules>
   <global>
      <models>
         <new_module>
             <class>New_Module_Model</class>
         </new_module>
      </models>
   </global>
   <crontab>
     <jobs>
        <new_module>
            <schedule><cron_expr>*/1 * * * *</cron_expr></schedule>
            <run><model>new_module/observer::test</model></run>
        </new_module>
     </jobs>
  </crontab>
</config>

Please note that the model tag is the same used in the run/model tag in the crontab job.

For this example, the job will be run every minute.

As a reference, this is the syntax of the cron_expr:

  • Minute: */5
  • Hour: *
  • Day of the Month: *
  • Month: *
  • Day of the Week: *

In app/code/local/New/Module/Model/Observer.php
class New_Module_Model_Observer
{
    public function test()
    {
        //Do something amazing
        return $this;
    }
}

THAT’S ALL, NOW TO TEST:
1) Refresh the cache
2) Delete everything in the cron_schedule table.
3) Run the following command to schedule all the jobs, you will notice that the cron_schedule table will be filled with some entries, you should also see the entry new_module .

 php -q path/to/my/magento/root/cron.php

4) Run it again and your cron job will be executed.