Thursday, 25 October 2012

MCD: Setting up cron job

As any complex system, Magento has a lot of tasks that need to be executed periodically. Here are some of these processes: 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, etc.

For that purpose we need to setup a cron job on a server. From Wikipedia we know that cron is the time-based job scheduler. Cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates.

To set up a cron job, first of all we should make our server run cron.php intermittently (that is located in Magento installation root). For that purpose Magento developers provide us with a shell script –, which is also located in installation root. Depending on your operational system, you need to edit either crontab on UNIX/BSD/Linux, using crontab -e command, or add a new task using Scheduled Tasks service for Windows. More information on this topic can be found on Magento Wiki page or in a Sweet Tooth manual.

cron.php file

Let’s have a look
try {
} catch (Exception $e) {

If we throughly look at these three lines of code and investigate which methods they call further, we can see that after initialization of config file for crontab section Magento finally invokes Mage_Cron_Model_Observer->dipatch() that does the following:

1. Process scheduled cron queue: Magento reads the cron schedule table for jobs that need to be executed this very second and jobs that should have already been executed, i.e. with timestamps in the past, that haven’t expired. The expiry limit is also a parameter, configurable in the admin panel. After all the work, dispatch method calls two generate() and cleanup() methods

2. Generate tasks schedule: Mage_Cron_Model_Observer->generate(), this method searches final configuration file for content of <crontab> nodes ($config = Mage::getConfig()->getNode(‘crontab/jobs’); ), reading <schedule><cron_expr> elements to find out when and how often they need to be executed and pulls this data into the cron_schedule table.

3. Cleanup: Mage_Cron_Model_Observer->cleanup(), this method deletes completed (with ‘success’ status) or missed ($time < $now – $scheduleLifetime, where $scheduleLifetime are set in Magento admin area) jobs from cron_schedule DB table.

cron_schedule table

Cron Schedule Table

Refer to this source while preparing for the exam.

schedule_id – unique proccess id
job_code – job identifier from configuration
status – can be one of the predifened statuses: 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, i.e. when server executes cron.php
scheduled_at – date/time when the task is planned to be executed, that is specified in <schedule> node of the config file
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.

Set up cron in Magento admin area

Cron (Scheduled Tasks) can be set up from the admin panel. The path is System -> Configuration -> System -> Cron (Scheduled Tasks)

There are six settings here. Please, note that the time is measured in minutes. Even though Magento has predifened settings for all of them, you can tune everything according to your needs.

Generate Schedules Every: schedules will be generated with setup frequency.

Schedule ahead for: schedules will be generated for this amount of time ahead.

Missed if not run within: if cron.php was executed within setup minutes after the task was scheduled, it will be executed. Otherwise, Magento will mark it as ‘missed’ in cron_schedule table

History cleanup every: Magento will clean up history not more than setup amount of minutes.

Success history lifetime: tasks with ‘success’ status will be stored in cron_schedule table for this amount of minutes.

Failure history lifetime: Tasks that have status ‘error’ and ‘missed’ will be stored in cron_schedule table for this amount of minutes.

Set up a cron job for custom extensions

Here is how config of our custom extension will look like:

                <schedule><cron_expr>*/15 * * * *</cron_expr></schedule>

<cronjob_code> – should be unique identifier, will be used as job_code in cron_schedule DB table

<schedule><cron_expr>* * * * *</cron_expr></schedule> – each asterisk stands for time period corespondingly: minutes, hours, days, months, years. If you leave it this way (* * * * *), cron job will be executed every minute. In our example, cron job will be run every 15 minutes <schedule><cron_expr>*/15 * * * *</cron_expr></schedule> or we can use alternative syntax to do that <schedule><cron_expr>0,15,30,45 * * * *</cron_expr></schedule>. If you want, for example, to run your job at 3 a.m., you need to do your cron expresion this way: <schedule><cron_expr>0 3 * * *</cron_expr></schedule>


Your modulename and modelname should be written in lowercase and stored according to certain (Magento Factory method) rules. methodName shoulb be written as is.

We need to write the code of our method in app/code/local/Namespace/Modulename/Model/Modelname.php

public function methodName() {
//put here whatever you need

That’s it.


No comments :

Post a Comment