Magento: Cron Jobs Setup for Custom Module
Cron Job is used to perform any action in a certain interval of time. In a Magento webshop, there are certain tasks that needs cron jobs to be run, i.e. these tasks/actions need to be performed periodically.
Here are some of them:-
- 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.
<config> ... <crontab> <jobs> <your_cronjob_name> <schedule> <cron_expr>*/0 0 * * *</cron_expr> </schedule> <run> <model>yourmodule/yourmodel::yourMethod</model> </run> </your_cronjob_name> </jobs> </crontab> ... </config>
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
The action that you want to perform in your cron job should be kept in the model function specified. From the code above, we see that our desired action code should be kept in the function yourMethod() of the class YourNamespace_YourModule_Model_YourModel.
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.
More information about:
- How to setup cron jobs in UNIX/BSD/linux and Windows systems
- Inner workings of Magento Crontab Mechanism
- cron_schedule database table
- Build-in Cron Jobs in Magento
Visit Magento Wiki: How to Set Up a Cron Job