How to Set Up a Cron Job

How to Set Up a Cron Job

A few features in Magento require a script to be run periodically. These features include, but are not limited to:

  • Catalog Price rules
  • Sending Newsletters
  • Generating Google Sitemaps
  • Customer Alerts/Notifications (product price change, product back to stock)
  • Automatic updating of currency rates
  • Scheduled DB logs cleanup

To run a script periodically, most operating systems have a built-in scheduled task spawning mechanism service (see OS -specific instructions below).

Magento and crontab

 

Magento allows you to schedule custom tasks in an XML configuration, in a similar manner to the UNIX crontab style. Here is an example from app/code/core/Mage/CatalogRule/etc/config.xml :

  1. <config>
  2. ...
  3.     <crontab>
  4.         <jobs>
  5.             <catalogrule_apply_all>
  6.                 <schedule> <cron_expr> 0 1 * * * </cron_expr> </schedule>
  7.                 <run> <model> catalogrule/observer::dailyCatalogUpdate </model> </run>
  8.             </catalogrule_apply_all>
  9.         </jobs>
  10. ...
  11.     </crontab>
  12. ...
  13. </config>

This example will run Mage_CatalogRule_Model_Observer::dailyCatalogUpdate method every day at 01:00am (0 1 * * *) .

 

Because you certainly want to extend this observer in your namespace directory, do not forget to make a rewrite node in config.xml in order Magento to call your observer and not the Mage core one. (EDIT: Could we have an example of this? What does a rewrite node look like? And which config.xml - the one for the module, or this one?) FIXME

 

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.

In UNIX/BSD/linux systems you will need to add this line (or a similar line) to your crontab:

  1. # for debugging purposes only:
  2. MAILTO=your.user@your.server.com
  3.  
  4. */5 * * * * /absolute/path/to/bin/php -f /absolute/path/to/magento/cron.php
  5.  
  6. # /absolute/path/to/bin/php - replace with path to your PHP5 CLI executable
  7. # example: /usr/local/php5/bin/php-cli
  8.  
  9. # in order to find what is the PHP CLI executable you can try to the following command in shell:
  10. # which php
  11.  
  12. # /absolute/path/to/magento/cron.php - replace with path to Magento installation
  13. # example: /home/user/public_html/magento/cron.php
  

UNIX/BSD/Linux systems have a crontab service. Crontabs are edited for each user using command crontab -e . (If you are logged in as root and want to edit a specific user’s crontab, you can use the command crontab -u user -e .) This will open an editor. It is possible that the contents will be empty if you have never set up crontabs for the current user.

The syntax for crontab file is:

  1. # all the comment lines will start with '#' character.
  2.  
  3. # in the beginning of the file set environment variables to be used in executed tasks:
  4. # ENV_VAR="value"
  5.  
  6. # the following line will send output for executed tasks to specified email:
  7. MAILTO=user@server.com
  8.  
  9. # declare running tasks in the following pattern:
  10. # <minute> <hour> <day-of-month> <month> <day-of-week> <command>
  11.  
  12. # this example will run /home/user/script1.sh every minute:
  13. * * * * * /home/user/script1.sh
  14.  
  15. # this example will run /home/user/script2.sh
  16. # every 15 minutes for 3 hours after midnight on weekdays during summer months:
  17. */15 0-2 * 6-8 1-5 /home/user/script2.sh

As you can see the syntax is very flexible. For more information visit the following link: http://www.google.com/search?q=crontab+syntax

If for some reason you can’t locate or access your php binary via crontab, you can also use curl or wget to activate cron.php

  1. */5 * * * * curl -s -o /dev/null http://www.yoursite.com/absolute/path/to/magento/cron.php
  

Windows has a Scheduled Tasks service which is accessible from the Control Panel.

Other solutions

 

If you do not have access to crontab on your service, you can set up the page that needs to be run periodically as a Home Page in you personal computer browser (http://yourdomain/yourmagentofolder/cron.php ). Every time you open a new window or tab, it will execute the scheduled task(s) on your server.

You could also set up a Scheduled Task on a computer to which you have access and which is usually running. It could then access a web accessible page that will run a cron job. In UNIX/BSD/Linux it can be done with wget or curl utilities.

Lastly, if either of these won’t work for you, there are a number of online cron services (complete list: http://onlinecronservices.com ) that may be useful. Many are free, but have restrictions on execution frequency or job count. Two reliable English services tested are: http://cronless.com and http://onlinecronjobs.com .

Inner workings

 

Magento crontab mechanism is triggered periodically using system cron job outlined above.

The call is initiated in cron.php file:

  1. <?php
  2. // initialize configuration and load event observers only from /crontab/ section
  3. Mage:: getConfig ( ) -> init ( ) -> loadEventObservers ( 'crontab' ) ;
  4.  
  5. // initialize crontab event area
  6. Mage:: app ( ) -> addEventArea ( 'crontab' ) ;
  7.  
  8. // dispatch 'default' event for observers specified in crontab configuration
  9. Mage:: dispatchEvent ( 'default' ) ;

This sequence will invoke Mage_Cron_Model_Observer→dispatch() , which in turn will:

  1. execute scheduled tasks
  2. generate future scheduled tasks if needed
  3. clean up history of scheduled tasks

Tasks are scheduled for each time the job needs to be run based on

  1. <schedule> <cron_expr> 0 1 * * * </cron_expr> </schedule>

expression and stored in cron_schedule table. Each record consists of the following fields:

  • schedule_id - unique identifier for scheduled task
  • job_code - job identifier from configuration
  • status - can be one of pending, running, success, missed, error
  • messages - custom text reported by method that was executed by the job
  • created_at - date/time when the task was created at
  • scheduled_at - date/time when the task is planned to be executed
  • executed_at - date/time when the task was actually executed (null prior to execution)
  • finished_at - date/time when the task finished execution (null prior to execution)

When schedules are generated, status is set to pending , created_at to now() and scheduled_at to target date/time.

When pending schedules are executed, status is set to running and executed_at to now() .

When scheduled task is finished successfully, status is set to success and finished_at to now() .

When scheduled task has thrown an exception, status is set to error and finished_at to now() .

If task status is pending and scheduled_at is older than “Missed if not run within” configured value, status is set to missed .

Error logging

 

TODO: add documentation on whether there is any error logging or not, and how to check it.

Configuration

 

You can fine tune execution and scheduling of Magento cron jobs in Admin > Configuration > System > Cron

  • Generate schedules every [ A ] (minutes)

New schedules will be generated not more frequently than A minutes.

  • Schedule ahead for [ B ] (minutes)

New schedules will be generated for B minutes ahead.

  • Missed if not run within [ C ] (minutes)

If cron.php was executed within C minutes after the task was scheduled, it will be executed. Otherwise it will be marked as missed

  • History cleanup every [ D ] (minutes)

History cleanup will happen not more frequently than D minutes.

  • Success history lifetime [ E ] (minutes)

Successfully finished scheduled tasks will remain in database table for E minutes.

  • Failure history lifetime [ F ] (minutes]

Failed and missed scheduled tasks will remain in database table for F minutes.

Magento's Cronjobs

 

The following cronjobs come along with your Magento install and can be found in the module’s config.xml.

Module Cronjob Cron syntax Frequency
CatalogIndex reindexAll 0 2 * * * Daily at 02:00am
CatalogIndex runQueuedIndexing * * * * * Every time cron is run
CatalogRule dailyCatalogUpdate 0 1 * * * Daily at 01:00am
Directory scheduledUpdateCurrencyRates  Admin→System→Configuration→Currency Setup
Log logClean */10 * * * * Every 10 minutes
Newsletter scheduledSend * * * * * * Every time cron is run, also see Newsletter settings
ProductAlert   Admin→System→Configuration→Catalog
Sales cleanExpiredQuotes 0 0 * * * Daily at midnight
Sitemap scheduledGenerateSitemap  Admin→System→Configuration→Google Sitemap

The above table lists the cronjobs in Magento 1.3.0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值