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 noticed 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.

 

Create and test a custom cron job in Magento 2016-05-18T08:45:52+00:00 Soipo

Comments are closed.

%d bloggers like this: