How to setup a cron job in Magento module?

In your modules config.xml put the following:

<config>
    <global>
        <models>
            <roomstoryinvoicecron>
                <class>Roomstory_Invoice_Model</class>
            </roomstoryinvoicecron>                         
        </models>
    </global>
    <crontab>
        <jobs>
            <roomstoryinvoicecron>
                <schedule>
                    <cron_expr>*/10 * * * *</cron_expr>
                </schedule>
                <run>
                    <model>roomstoryinvoicecron/observer::setStatus</model>
                </run>
            </roomstoryinvoicecron>
        </jobs>
    </crontab>
</config>

In app/code/local/Roomstory/Invoice/Model/Observer.php add the following:

<?php
class Roomstory_Invoice_Model_Observer {
    public function setStatus() {
        Mage::log("WORKS!");
    }
}

Make sure logging is enabled and it should work, check the log to be sure ;)


Be sure to add Magento cron.sh file in crontab

crontab -e

*/5 * * * * /bin/sh /path-to-magento/cron.sh

 <crontab>
        <jobs>
            <CompanyName_ModuleName>
                <schedule>
                    <cron_expr>*/5 * * * *</cron_expr>
                </schedule>
                <run>
                    <model>ModuleName/observer::setStatus</model>
                </run>
            </CompanyName_ModuleName>
        </jobs>
    </crontab>

and create Observer.php file in Model with

    class CompanyName_ModuleName_Model_Observer extends Mage_Core_Model_Abstract
{

   public function setStatus()
   { 

   }
}

You can easily create a module for cron job just follow the following steps:

Create Config.xml file and set cron job in it.

<?xml version="1.0"?>
<config>    
<crontab>
        <jobs>
            <Namespace_Module>
                <schedule>
                    <cron_expr>* * * * *</cron_expr>
                </schedule>
                <run>
                    <model>module/observer::method</model>
                </run>
            </Namespace_Module>
        </jobs>
    </crontab>
</config>

Your observer method:

  class CompanyName_ModuleName_Model_Observer extends Mage_Core_Model_Abstract
{

   public function setStatus()
   { 
//your action
   }
}

now last step go to your hosting cpanel and set path and run time of cron.php file in cron job section

by default you can set path like php -f /home/mercodec/public_html/cron.php in magento.