PHP CLI and Cron - Cron
(Page 2 of 3 )
What is Cron?
Cron is basically a daemon used to initiate timed events. As mentioned before a great use of this is to cleanup a set a database tables at a specified time. It is usually automatically installed by default with most Linux distributions.
How to Use Cron?
To access Cron simply type crontab -e, this usually invokes VI the default editor used to open crontab text file. To change the default editor simply edit the /etc/.bash_profile then find the line that says editor=vi and change it to your favorite editor; for example, editor=emacs, editor=jove or editor=pico. Along with crontab -e, creation of crontab entry there is crontab -l which will display the contents of the crontab file and crontab –r will clear the contents of the current crontab file.
There may or may not be already entries in the file. To add a new Cron entry you first need to understand what the file layout is. The first set of numbers indicates the time to initiate or trigger the job the second part after the numbers is the process or task you want to run at the specified time.
The first six fields (the time) are defined as follows
| FieldFONT> | Definition |
| Minute | 00 to 59 |
| Hour | 00 to 23 (military time) |
| Day | 1 to 31 |
| Month | 1 to 12 |
| Weekday | 0 to 6 (where 0 is Sunday) |
An example of what a crontab entry looks like
0 2 1 * * echo "Hello World" 2>&1 /dev/console
This will output Hello World to the console at 2 am the first day of every month. The * is a wildcard, meaning to match all values. You can also specify a set and range of times. Taking the same example, say you want to execute now at 2am and 2pm. The entry would look like this
0 2,14 1 * * echo "Hello World" 2>&1 /dev/console
Notice the comma indicates more then one time for that field. Say now wanted Hello World to output every hour from 2am to 2pm the entry could look like this
0 2-14 1 * * echo "Hello World" 2>&1 /dev/console
PHP and Cron
This is actually quite easy now that you know how to use both PHP CLI and Cron. It is just a matter of using them together. Referring to the Hello World php script phpcli.php, assuming resides it /home/phpscripts. Simply add an entry into Cron invoking this process everyday at 1 pm, the entry should like the following:
0 13 * * * /usr/bin/php -f /home/phpscripts/phpcli.php
Next: Final Words >>
More PHP Articles
More By Jason Lam