How to use Magento Cron Job

Magento Cron Job

Software automation is carried almost everywhere. Since it is hard to perform many actions manually such as taking daily database backups etc. many tools are utilized to perform these tasks automatically. One of such tools is Cron Job. It is basically a Linux service that runs in background and can perform repeating tasks for you on pre-defined intervals. Cron Job is a used professionally in small to large size companies. In Magento it is used at many places such as keeping catalog indexes up to date, refreshing catalog price rules automatically. These tasks cannot be performed manually on daily bases and are vital to keep running your Magento in healthy state.

Allowed ranges for Crontab fields

To give you an example of running Cron in Linux environment, see below command,

20 22 8 07 * /home/PC1/full-backup

It means on 20th minute, at 10 PM, and 8th day of July a full backup is to be taken automatically.  How does Cron works actually is that it looks for Crontab files in its spool area (var/spool/cron/crontabs). It then checks these files every minute to see if it should start running any job. It will also check if any change is made to Crontab files and will appropriately load them.

Using Magento Cron Job:

Type following to open Cron tab as the logged in user,

crontab –e

or use below method  in case there should be different user,

crontab –u username -e

Crontab is a program that runs Cron tasks. Each user can have a separate Crontab. Commands are executed under that specified user.  Crontab files should not be accessed directly and have to be accessed by using this utility.  First command above will open up crontab text editor vi. Each line in the text file is referred to as Cron job.  Each job contains 6 sections separated by single space. 6th position indicates the task that will be executed by first 5 sections which tells the time interval to run that task periodically. Once this files is saved. Cron jobs will run automatically and there is no need to do anything else.  Other ways of doing same thing in Magento is as below and that is by using scripts,

*/5 * * * * wget -q http://www.abc.com/cronscript.php

Wget formerly known as GerUrl retrieves content from web servers and can be used to run a Cron script as indicated above. Or you can use PHP to do this,

*/5 * * * * /php path -f /path to cronscript

You can test if your Cron job runs successfully by setting an erroneous command to see if your receive any error every five minutes e.g.

MAILTO=you@yourdomain.com

*/5 * * * * wget-erroronous command -q http://www.abc.com/cronscript.php

Adding Cron to Magento Modules:

You can also add Cron jobs to Magento Plugins by changing your modulus’s config.xml as below,

 That will run your task every 15 minutes on the quarter hour. So now you can sit relaxed and let Cron take care of your jobs.

This blog was created with FME's SEO-friendly blog