11 Nov 2013

Magento: Setup Cron Jobs In Custom Module



Sometimes in magento we need some task to be run , i.e. these tasks/actions need to be performed periodically like:………….  

- Refreshing Catalog Price Rules
- Sending Newsletters to customers
- Generating Google Sitemaps and submitting it to Google
- Sending Customer Notification about product price change or product back in stock
- Updating currency rates
- Making backups
- Cleaning logs 




To setup cron jobs for your custom module, you need to add the following piece of code into the config.xml file of your module.






The desired action code should be kept in the function yourMethod() of the class YourNamespace_YourModule_Model_YourModel.
The cron syntax in the above xml code is */0 0 * * *. This means that the cron job will run daily at midnight.

Some examples of cron syntax are:

*/0 1 * * * = Daily at 1 am
*/0 2 * * * = Daily at 2 am
*/* * * * * = Every time cron is run
*/5 * * * * = Every 5 minutes
*/10 * * * * = Every 10 minutes

* * * * * command to be executed
- - - - -

| | | | |

| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)

| | | ------- Month (1 - 12)

| | --------- Day of month (1 - 31)

| ----------- Hour (0 - 23)

------------- Minute (0 - 59)


How do I use operators?

An operator allows you to specifying multiple values in a field. There are three operators:
  1. The asterisk (*) : This operator specifies all possible values for a field. For example, an asterisk in the hour time field would be equivalent to every hour or an asterisk in the month field would be equivalent to every month.
  2. The comma (,) : This operator specifies a list of values, for example: "1,5,10,15,20, 25".
  3. The dash (-) : This operator specifies a range of values, for example: "5-15" days , which is equivalent to typing "5,6,7,8,9,....,13,14,15" using the comma operator.
  4. The separator (/) : This operator specifies a step value, for example: "0-23/" can be used in the hours field to specify command execution every other hour. Steps are also permitted after an asterisk, so if you want to say every two hours, just use */2.
The cron job tasks are stored in cron_schedule table. There is a ‘status‘ field in this table. The value of this field can be pending, running, success, missed, error

Initially the status is set as ‘pending’. Pending then changes to ‘running’. From the running state, the status can either become ‘success’ (if the task is finished successfully) or ‘error’ (if there is an exception thrown). If the task fail to run within the configured time value, then the status is set as ‘missed’.

To execute all these configured tasks, the cron.php file located in the Magento root will need to be run periodically, for example every 15 minutes. Basically, this script will check if it needs to run any tasks, and if it needs to schedule any future tasks.