Posts Tagged ‘crontab’

Using Crontab To Schedule Execution Of PHP Scripts

Posted in Misc on April 18th, 2009 by helloworlder – 2 Comments

Crontab (cron table) is a UNIX program that allows you to schedule the execution of shell commands. You can use it to run PHP scripts at set intervals.

The first step is to enter this in the shell:
sudo crontab -u username -e
Replace username with your username. The -e flag means edit.

That will open the text editor where you will write your crontab command. Before typing anything in you need to know about the crontab syntax, which goes like this:

minute hour day_of_month month day_of_week command

That alone probably won’t make much sense. Don’t worry. The following examples of its usage will make it clearer:

This is how you would execute a script on the 10th minute of every hour, every day of the month, every month, every day of the week:
10 * * * * /usr/bin/php -q /home/username/public_html/your_website/your_script.php

This is how you would execute a script at midnight (0th minute of the 0th hour) on the 1st of the month, every month, every day of the week:
0 0 1 * * /usr/bin/php -q /home/username/public_html/your_website/your_script.php

This is how you would execute a script every 20 minutes, every day of the month …
20,40 * * * * -q /usr/bin/php /home/username/public_html/your_website/your_script.php

As you may have guessed, the * symbol means “every”. So, the * in the first position would mean to execute your script every minute.

The /usr/bin/php is the path to the PHP executable. It’s possible that you’ve installed PHP in a different location.

The -q is a php flag telling php to supress the HTTP header since you are simply running a script.

Once you save the text file, your cron table will be in operation.

So with all that out of the way, you still might ask, what if my script has output i.e. I use the echo functions? The output cannot be directed to the screen as usual. You will receive e-mail containing the output every time the script is run. If you don’t need to echo anything, then don’t and you won’t receive e-mail.


Easy AdSense by Unreal