How to use Cron

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to use Cron

Post by Tony » Sun Nov 29, 2009 4:37 am

Cron is used to execute a script or command at a specified interval or point in time. The control file is a crontab file. A crontab file is made up of one line per entry. An example crontab entry looks like this:

0 * * * * php $HOME/cron.php >>$HOME/cron.log 2>>$HOME/cron.err

In the above example, the script cron.php is executed every hour on the hour.

An entry line contains nine fields, which must be separated by white space (tabs or spaces). The fields are:
  1. Minute of the hour in which to run (0-59)
  2. Hour of the day in which to run (0-23)
  3. Day of the month (0-31)
  4. Month of the year in which to run (1-12)
  5. Day of the week in which to run (0-6) (0=Sunday)
  6. Optional shebang, if needed (for running php scripts in the above example, may vary depending on your host config)
  7. The path/command to execute (note that $HOME gets you to your user root)
  8. The log file - which begins with >>
  9. The error log file - which begins with 2>>
An entry in the first five columns can consist of:
  • A number in the specified range
  • A range of numbers in the specified range; for example, 2-10
  • A comma-separated list consisting of individual numbers or ranges of numbers, as in 1,2,3-7,8
  • An asterisk that stands for all valid values
  • An asterisk with a /value, for example */10 in the minute location would mean very 10 minutes
  • Do not user tabs or spaces as they are the delimiters between columns
Some considerations are:
  • If you want to run a PHP script you should include the shebang (php in the above example)
  • If you want to pass variables to a PHP script the standard search argument syntax for passing $_GET variables will not work. You can use the format path/script.php variable1=value variable2=value2 (note the arguments are simply separated by a space).
  • If you want to run a PHP script you should include the full UNIX path (i.e. $HOME/. . ./script.php ). $HOME points to your FTP root directory.
  • The log files should include the full UNIX path
  • Your crontab must contain one blank line at the end
A line that begins with a # is treated as a comment line.

To create a crontab file:
  1. Create an empty text file (named crontab.txt) in Notepad
  2. Add the contents of your crontab file, you can have as many entry lines as you want
  3. Your crontab must contain one blank line at the end
  4. Upload the file to your package in the etc directory
  5. Rename the file crontab (with no extension)
Please note that your webhost may supply a control panel that just asks for the cron command. You may not have access to the crontab file. If that is the case, just enter the cron command in the place requested and ignore the instructions about the crontab file.
Post Reply

Return to “PHP & MySQL”