This tutorial explains how to automate the execution of PHP scripts using a Linux utility called crontab. A crontab file is generated for each user on your server. Be sure to have a Mail Transfer Agents (MTA) such as Postfix installed. Cron job statuses (fails, successes, and reasons) are sent via an internal mail client to the user who owns the job. If there is no MTA installed, crontab will discard the output.
On Ubuntu, the cron job log file is views via:
grep CRON /var/log/syslog
Creating and Editing Crontab Entries
In this example we’ll create a cronjob that will run our PHP script awesome-script.php
, at 8:30 AM Monday through Friday.
To begin, open the crontab file by typing:
$ crontab -e
Next, paste the following into the file:
30 08 * * 1-5 cd /home/username/public_html/domain.com/public/my-cool-app/; php awesome-script.php
Just save and exit and you’re done!
Viewing Crontab Entries
To view the logged-in users crontab entries type crontab -l (-l is a lower case “L”) from your unix account as shown below.
$ crontab -l
Crontab Time Scheduling Formats
MM HH DD MM DOW
To specify, every time period (e.g., everyday of the week) use a single *
symbol instead of a number. Here’s a table of crontab fields and allowed values:
Field | Description | Allowed Value |
---|---|---|
MM | Minute field | 00 to 59 |
HH | Hour field | 00 to 23 |
DD | Day of Month | 01-31 |
MM | Month field | 01-12 |
DOW | Day Of Week | 0-6 (where: 0 = Sunday) |
CMD | Command | Command to run |
Summary of Cron Commands
$ crontab -e #Create/Edit cron jobs in nano $ crontab -l #List current cron jobs $ crontab -r #Remove all cron jobs