Yesterday I came to a problem which could be solved by a PHP script ran at regular intervals on a web server, and as I have not touched crontab in a while I thought it worth a quick summary.
Without a native way for PHP scripts to schedule tasks it is often useful to couple server-side scripting with user-level scheduling using cron.
Running A PHP Script From CLI
To make a PHP file executable, the location of the PHP interpreter must be included:
Make sure this appears first in the file with no hidden characters at the end of the line (open with vim to be sure, some editors like nano can hide some characters).
A permissions change is also required to make the script executable:
chmod +x [filename.sh]
This will then allow you to simply call the file from terminal.
Alternatively the script can be passed straight to the php CLI tool using the -f flag:
php -f [script.php]
In the PHP script itself it is often best to stick to absolute paths for includes, you will not have the benefit of $_SERVER variables normally populated by Apache and if you use relative paths you are likely to have a bad time.
Running The Cron Job
To edit the crontab file for a user:
Each line in a user’s crontab will run a command at the defined intervals, with five whitespace delimited values for the intervals followed by the command itself:
minute hour dayofmonth month dayofweek command
Using * means all, so * for hour would run the command at the defined point in every hour. You can also use the format */x to tell a command to run at every x increment. For example:
0 2 * * 0 php -f script.php //2am, every Sunday
1 0 * * * php -f script.php //One past midnight, every day
*/1 * * * * php -f script.php //Once a minute
You can check the lines from a user’s crontab using the -l flag:
It can also be useful to check that the service is running using ps and grep:
ps -A | grep cron
Control the service with:
sudo /etc/init.d/cron start
sudo /etc/init.d/cron stop
sudo /etc/init.d/cron restart
Note that some distros seem to have crond instead of cron here.
A simple method I have used in the past to check if a crontab file is running as and when intended is to add a touch command with the same scheduling as the command you are setting up e.g.:
*/1 * * * * touch ~/tempfile //touch tempfile in home directory every minute