switch



How To: Run periodic code in Magento

February 13, 2013 at 8:59 am, Category: Programming, Web Development, by Dave

If you wish to run a piece of code periodically, for example every hour, or at midnight every day, the best way to do this is to put it in a CRON task.

Magento manages its own CRON tasks using the internal “crontab” functionality. This queues up all the Magento code that wishes to be automatically run without user intervention.

This feature allows you to safely and easily create your own extension and lets you add your own tasks to Magento’s CRON functionality.

Let’s begin…

All it needs is 3 simple files.

You will need to create the folder structures to accommodate the files.

/app/code/local/Mycompany/Myextension/etc/config.xml
<config>
<modules>
<Mycompany_Myextension>
<version>0.1.0</version>
</Mycompany_Myextension>
</modules>
<global>
<models>
<myextension>
<class>Mycompany_Myextension_Model</class>
</myextension>
</models>
</global>
<crontab>
<jobs>
<mycompany_myextension_taskname>
<schedule><cron_expr>*/30 * * * *</cron_expr></schedule>
<run><model>myextension/myextension::cron</model></run>
</mycompany_myextension_taskname>
</jobs>
</crontab>
</config>

Note: the line

<schedule><cron_expr>*/30 * * * *</cron_expr></schedule>

This sets the frequency at which your cron task will execute, and is currently set to every 30 minutes. For more information on CRON expressions see here.

/app/etc/modules/Mycompany_Myextension.xml
<?xml version="1.0"?>
<config>
<modules>
<Mycompany_Myextension>
<active>true</active>
<codePool>local</codePool>
</Mycompany_Myextension>
</modules>
</config>
/app/code/local/Mycompany/ Myextension/Model/Myextension.php
<?php
class Mycompany_Myextension_Model_Myextension extends Mage_Core_Model_Abstract {
public function _construct() {
parent::_construct();
$this->_init('myextension/myextension');
}
public function cron(){
// Your code goes here!
}
}

And that’s it!

Simply put your PHP code into the cron() method and it should run as frequently as you’ve specify in config.xml

If for some reason your code doesn’t run, check your system and/or exception log files for possible code errors, and check that your hosting solution has a CRON setup to run Magento’s cron.php

Additionally, check that the correct case is used in file and folder names and in the xml and php files for the extension and module names.

The extension files can be found here: Download ZIP.

Our Client Line Up

Terms and Policies: Privacy Policy | Terms and Conditions | Environmental Policy | Equal Opportunities Policy | Sitemap
© NuFuture Ltd 2005-2010. Company No: 05523340  |  VAT No: 865 6930 80  |  InfoLab21, Lancaster, Lancashire, UK