RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Writing and Automating PHP Crons in Windows and Linux

Find out how to automate PHP scripts so they run unattended at scheduled times on both Windows and Linux.

cron (an abbreviation for chronograph) defines a process used to execute a script, start a program, send a newsletter, backup a database, display a message, remove some unnecessary files at a specified date or time, or at a set interval. In general, any process that you want the computer to execute automatically is a cron. This article explains how you can run PHP scripts as crons.

PHP Crons and Linux
Linux has a good solution for managing processes that execute at specific times: the cron daemon (called crond). You define the scripts or commands that you want to run in "crontab" files. Crontabs represent a set of tasks performed chronologically; each line represents one entry. Each entry specifies information about how to perform a task, such as executing a script. These individual tasks are called "cron jobs."

Author's Note: Each user has a separate crontab file, so crons can be user-specific.

You execute a crontab file using this syntax:

   # crontab [--e [-u username] | -l [-u username] | 
      -r [-u username] | file] 
The —e argument means edit the file using the default editor (for example, vi). After editing, the file is installed as the crontab file for the current user in the cron directory. If the crontab file already exists it will be overwritten. The —l argument lists the file's contents, and the —r argument removes the file from the crontab directory.

The username that follows the —u (username) argument is optional, but specifies which crontab file the command affects. For example, a root user may include the username to specify the owner of a particular crontab file. If you don't specify the username argument, the crontab command affects the current user's crontab file. If the username argument is invalid the command generates an error.

The file argument in the example command replaces the specified crontab file with the file named in the file argument. The replacement file's content must conform to the daemon cron format, for the crontab command to work properly.

Crontab File Syntax
The syntax of this file is very important; if you get it wrong, your crontab will not function properly. Each line of the file must contain the six fields listed in Table 1, in sequential order. You must must separate the lines with a newline character.

Table 1. Crontab Line Fields: Each line in the crontab file must contain these six numeric fields in this specific sequence.
Field Description
Minutes Number from 0 to 59
Hours Number from 0 to 23
Day of month Number from 1 to 31
Month Number from 1 to 12
Day of week Number from 0 to 6, where 0=Sunday and 6=Saturday
Command Script name or command to execute

You can set the content for the first five fields in any of several ways:

  • As a number in the specified domain: For example, setting the Minutes field to 6 means the script will execute at the sixth minute.
  • As a range in the domain: For example, you might set the Hours field to 2-9 to execute a script every hour from 2:00 to 9:00 AM.
  • As a comma-separated list of values: For example, you might set the Hours field to 2,5,9 to execute a script at 2:00, 5:00, and 9:00 AM.
  • As an asterisk (*): The asterisk is a wild card that matches any number in the domain.
  • As an asterisk with an accompanying value: For example, */5 placed in the Minute field means that the script will execute every 5 minutes.
The sixth and last command argument specifies the script name or command to execute.

In addition to the required fields, you can optionally generate a log file or an error file using these optional arguments:

  • Log file: Specify a log file by using two right angle brackets (>>) followed by the log file name; for example, >>cron.log.
  • Error file: Specify an error file using the prefix 2>> followed by the error file name; for example, 2>>cron.err.
Crontab File Examples
In this section you'll see some crontab file examples that reference the mycron.php PHP script listed below. The script creates a file containing the date and time at which the script ran:

Author's Note The following script writes output to a logs subdirectory of the current directory. If you're following along, you must create that directory before running the PHP script.

      $currentDate = date('Y-m-d'); 
      $hf = fopen("./logs/".$currentDate."_log.txt","w")
            or die (" The file".$currentDate. 
            "_log.txt couldn't be created!");
      //Write the current date and time when the process is ruled
      $wrt=fwrite($hf,"***  [".date('Y-m-d H:i:s'."]   ***"));  
Example 1
To run the mycron.php script every Friday at 3:45 AM, your crontab file must contain the following content on a single line:

   45 3 * * 5  php  --q  path/mycron.php  
Example 2
To run the script every 20 minutes, on March 23rd, the crontab file would look like:

   */20  *  23  3  *  php --q  path/mycron.php
The php—q parameter in the preceding example is required to execute the script. The path argument represents the absolute path of the script.

If you want to specify URL paths instead of absolute paths, you'll need the wget packet. To check if the wget packet is installed, type the following command on an RPM system (Red Hat or Mandrake):

   #wget --help
If not, you can download wget. Follow the installation instructions on that page.

Example 3
With wget installed, you can now run this URL script every Monday, Wednesday, and Friday at 00:32 AM, using a crontab file that contains the following content on a single line:

   32  0  *  *  1,3,5  wget  http://www.yoursite.com/script.php

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date