Wednesday, June 17, 2009

Run PHP scripts automatically at intervals - use Cron Jobs

/*Automation may be needed in to order to run certain scripts at regular intervals for tasks like scraping , extracting or crawling data from web or do some regular tasks like sending emails or whatever.

To automate a script is simple. The webhost must provide cron facility. Cron is a utility which can be used to execute a set of commands at a given schedule of time.

For e.g. if a php script called regular.php is to be executed regularly every day or every month or on certain weekdays then cron can be configured to execute the script at defined schedules and hence automation is achieved. Since web hosts are alive and online most of the times the automation process is more useful when used on a web server rather than a home pc.

Cron can be configured from Cpanel and via ssh terminal as well.

To configure cron from ssh terminal simply login to your webspace using ssh.

The command crontab -l will show what schedules have already been made or what tasks are to execute according to current cron settings.

Cron settings consist of lines like this

* * * * * /command/to/execute

The 5 stars indicate the time to execute and the /command/to/execute is the path to the script or command which should be executed at that point of time.

If you put the regular.php script in the www folder on your webhost then the path could be :
/home/username/www/regular.php

So the command to execute it would be

php /home/username/www/regular.php

The above command needs a time schedule to run.

The 5 stars indicate the following

Minute Hour Day Month Day -- in that order

Minute - 0-59
Hour - 0-23
Day - 1-31
Month - 1-12
Weekday 0-6 (o= Sunday)
* means any

So to execute a script everyday
0 0 * * * - means At 00:00 anyday anymonth anyweekday

So the cron line would be
0 0 * * * php /home/username/www/regular.php

All such cron schedule lines can be written in a txt file and this cron file can be given to crontab to set the schedules using the following command :

crontab crontasks.txt

Another line that can be added on the top of the crontasks.txt file is
MAILTO=user@site.com

and this is the email address to which the execution results shall be mailed.

So the crontasks.txt file can look like this :

MAILTO=user@site.com
0 0 * * * php /home/username/www/regular.php

should be saved and the command :
$crontab crontasks.txt
would set it.

Before setting a new crontask set you may want to backup the previous set of cron tasks :
$crontab -l > oldcrontasks.txt

To check the schedules :

$crontab -l
will show all cron tasks.

crontab -r
will remove the cron tasks

So using crontab any php script or any other script or command can be executed automatically on server side.*/