We suppose you continue following our Magento certification-dedicated posts in our blog. This time we will describe how to set up a cron job.
Let’s start with server setup.
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 – cron.sh, 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
1 2 3 4 5 6 7 |
try { Mage::getConfig()->init()->loadEventObservers('crontab'); Mage::app()->addEventArea('crontab'); Mage::dispatchEvent('default'); } catch (Exception $e) { Mage::printException($e); } |
If we thoroughly 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
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:
1 2 3 4 5 6 7 8 9 10 |
<config> <crontab> <jobs> <cronjob_code> <schedule><cron_expr>*/15 * * * *</cron_expr></schedule> <run><model>modulename/modelname::methodName</model></run> </cronjob_code> </jobs> </crontab> </config> |
<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>
<run><model>modulename/modelname::methodName</model></run>
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
1 2 3 4 5 6 7 |
<?php public function methodName() { //put here whatever you need } |
That’s it.
Read our previous posts.
The Process and Configuration of Class Overrides in Magento. Register an Observer
Describing Class Group Configuration and Use in Factory Methods
Explaining how Magento loads and manipulates configuration information. Part II
Explaining how Magento loads and manipulates configuration information. Part I
Describing Methods for Resolving Module Conflicts
Class Naming Conventions and Their Relationship with the Autoloader
Hi guys
Last value of the cron is not year, but day of the week:
# * * * * * command to execute
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ └───── day of week (0 – 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
# │ │ │ └────────── month (1 – 12)
# │ │ └─────────────── day of month (1 – 31)
# │ └──────────────────── hour (0 – 23)
# └───────────────────────── min (0 – 59)
”
Hi Sergei,
Thanks for your tutorial, you just forgot to mention something important, you need to declare your model class otherwise your custom module method will not be found:
Namespace_Module_Model
” – Jonathan
Its been about 2 years, still no update on the post.
Hello Milen. A couple of weeks ago some developers could not schedule their exams and it was not clear if certification continues. Now we are going to write new articles about Magento Certification. Just follow our rss feed to be aware of updates.
Looks like the very good theme for Magento Certification is already dead. :(
Hi Jonathan,
Thank you for your comment. Will update the post soon.
Hi Sergei,
Thanks for your tutorial, you just forgot to mention something important, you need to declare your model class otherwise your custom module method will not be found:
Namespace_Module_Model
Working with Magento cron? Want a gui incl. a nice timeline view and some command line tools to handle cron tasks? Then you should definetly checkout my free Magento module Aoe_Scheduler
Bye, and have a nice day,
Fabrizio
Hi Fabrizio,
When I wrote this I was thinking to end the article by providing a link on your extension. It’s absolutely brilliant and helped me to find the reason of a tricky bug which was somehow connected to cron (some proccess run smoothly and some not).
Thank you!