Cron for PHP with quiet option

Posted under » PHP » Ubuntu » Linux on 18 November 2009

Cron (short for chronology) is a Linux module that allows you to run commands at predetermined times or intervals. In Windows, it's called Scheduled Tasks.

We all know how run scripts but what about PHP scripts? Here, I will not cover the normal crons but specifically crons that run PHP and on Ubuntu.

First create the php file to run. It could be external or localhost. Try running it using the wget command

# wget

If this work, then it will work with crons. I got this guide from here.

In case you want to use the traditional cron, you can do the normal way

An unlikely example. Every Monday, if it falls on 2nd June at 3:15pm.

15 15 2 6 1  wget

You can use comma so you don't have to make extra lines. Eg... every hour at 41st and 42nd minute.

41,42 * * * *  wget

Make sure you have an empty space at the bottom. Save the file as somecron.txt

A newbie mistake is to set the hour but not the minutes. like so.

* 09 * * *  wget

This will make the cron execute every minute at 9am! The correct way is to

10 09 * * *  wget

However if you want to send every 10 minutes

*/10 * * * *  wget

This way, once it execute at 9.10 it will stop.

Now put this file in a folder. "/var/someplace/"

Now issue the crontab command that will list your current crons

# crontab -l

To add the cron you just created

# crontab /var/someplace/somecron.txt

You can edit the cron if you wish

# crontab -e

To remove all crons

# crontab -r

Then list them out again. You will see your crons being listed. This will stay in the memory. Even if you replaced the somecron.txt contents, it will still do the crons that is in the memory. If you reboot your server, crons that is in the memory will be lost.

Just a matter of interest, all crons are created and located at "/var/spool/cron/crontabs/" and for all wget, the output will reside at /root. In most cases you want to silence them. Otherwise, your /root folder will be bloated. In addion, you or root will also receive an email from cron with the command output.

If you are getting mails.. they probably come from "/etc/cron.d".

wget -O - -q -t 1
wget –quiet –output-document /var/tmp/yahoo.html
wget >/dev/null 2>&1

where -O means output instead of file, -q means quiet and -t 1 means try 1x.

web security linux ubuntu GIT svn Raspberry apache mysql php drupal cake symfony javascript Ajax css