Writing and Automating PHP Crons in 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.

      

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

Scheduling Crons with cPanel
The graphical web-based control panel cPanel (see Figure 1) lets you manage your domain through a web interface. Using cPanel you can manage all aspects of mail, crontab tasks, backup, FTP accounts, CGI scripts or web site statistics, and many other tasks.

Among those is “Cron Jobs,” an automated process that runs tasks at predefined date and time intervals on your web server (see Figure 2). As examples, you can create cron jobs to delete temporary files every month to save disk space, or to copy a MySQL database to a separate location as a backup once each week.

?
Figure 1. cPanel Main Page: cPanel is a tool that lets you manage various tasks, including cron jobs, using a graphical web interface.
?
Figure 2. cPanel Cron Jobs: You can opt to use either the Standard or Advanced (Unix Style) “experience level;” Standard is recommended.

?
Figure 3. Standard Cron Job Screen: Specify the output location, the job you want to run, and select the time and frequency of your job.

There are two ways to create a cron job using cPanel: Standard, and Advanced (Unix style).

Create a Standard Cron Job
The Standard method lets you configure the time and frequency of your job. This is the simplest method and is recommended.

You’ll see the Standard Cron Manager screen (see Figure 3). To create a Standard cron job, follow these steps:

  • Enter the email address where you want the output of your cron job files to be sent.
  • The first option in the “Entry 1” panel is “Command to run.” Enter the command or path to a script/file that you want the cron job to run.
  • Next, set the time and frequency of your cron job using the five time/date-related fields shown in Figure 3.
  • When you’re done, click the Commit Changes button to create the cron job entry, or click the Reset Changes button to undo your modifications.
  • You’ll see a confirmation page showing a “Cron Updated!” message. Click on the Go Back button to return to the main Cron Job screen.
?
Figure 4. Advanced Mode: The figure shows the screen where you configure the time and frequency of your job using Advanced mode.

Create an Advanced Cron Job
The Advanced (Unix Style) method (see Figure 4) lets you enter the time parameters in Unix style.

  • Enter the email address if you want to receive confirmation emails after the job executes.
  • Configure the time and frequency of the job and enter the cron command or path to the script/file you want the cron job to run.
  • Click Commit Changes to create the cron job entry or click Reset Changes button to undo your modifications.
  • A confirmation page will appear showing the “Cron Updated!” message. Click on the Go Back button to return to the main Cron Job screen.

Both the Standard and Advanced methods create cron jobs, but the advanced interface is closer to the Unix command-line way of creating a job.

Running PHP Crons in Windows Vista
To execute PHP scripts in Windows you have two options: You can run crons manually or use the Windows Task Scheduler service to schedule them to run at specific times and frequencies.

Again, the examples here all use the PHP script mycron.php listed earlier.

Running crons manually is not typically an effective solution, because it requires a human to physically type the command(s). You can simplify the process by creating a batch file. First, create a text file with a .bat extension (cron.bat in this case) and add two lines to it, using the following syntax:

   SET PATH="{php.exe HOME}";   start php.exe phpscriptname.php

For example, to run the mycron.php script, you would write:

   SET PATH="D:PHP"   start php.exe mycron.php

The first line sets the current directory to the location of the PHP application server executable file, and the second line starts the PHP script in a new window.

Place the PHP script, mycron.php, in the same directory as the batch file (or update the path in the batch file to point to the location of mycron.php).

Every time the operating system runs the crontab, Windows will open a MS-DOS window, run the script, and close the window when the script completes. You’ll see any output in the logs subdirectory.

Your other option is to use the Task Scheduler Windows service. All versions of Windows since at least Windows 95 can use Task Scheduler to schedule jobs that run at specified times; however, Windows Vista runs the tasks more predictably and securely then older versions of Windows. The most important new features of the Task Scheduler in Vista are:

  • Multiple conditions that can restrict a task to run only when the machine is in a given state. For example, you can schedule a task to run only when the computer is in an idle state, on AC power source vs. battery power, has network connectivity, or only when the computer is “ON” versus in a sleep state.
  • Task Scheduler in Windows Vista supports triggers that can launch tasks at machine idle, startup, or logon.
  • Administrators can use settings to instruct Task Scheduler what actions to take if a task fails to run correctly. If a task fails, administrators can specify how many times to retry it. They can also set the maximum execution time for a task, which will stop the task if it runs too long.

To read more about the new Task Scheduler features of the Windows Vista and to see a comparison between the Windows Vista vs Windows XP and Windows Server 2003 versions follow this link: http://technet.microsoft.com/en-us/appcompat/aa906020.aspx.

To run a PHP script using Task Scheduler in Windows Vista follow these steps:

  1. Open Task Scheduler using Start ( All programs ( Accessories ( System Tools ( Task Scheduler.
  2. In the Task Scheduler window, choose Action ( Create Task?
  3. In the General tab of the Create Task window enter a name for the task and (optionally) a description (see Figure 5).
  4. In the Actions tab of the Create Task window, click the “New?” button (see Figure 6, top), and then select an action (see Figure 6, bottom). To run a PHP script choose the “Start a program” option.
  5. ?
    Figure 5. Task Scheduler: The General pane accepts a name and optional description for the task, and provides some other settings.
    ?
    Figure 6. Task Scheduler Actions Tab: To create a new action, click the New… button and select the “Start a Program” action.

  6. In the Conditions tab, specify the conditions under which you want the task to run; the task will not run until the conditions you set evaluate to true (see Figure 7).
  7. You can use the Settings tab (see Figure 8) to specify some additional settings that affect task behavior, such as what to do if the task fails or runs longer than some maximum allowable time. When you’re done, click OK.
  8. ?
    Figure 7. Task Scheduler, Conditions Tab: Specify the condition(s) under which the task should run.
    ?
    Figure 8. Task Scheduler, Settings Tab: On this tab, you can specify additional settings for the action, such as the maximum allowable time, and the number of restart tries.

  9. Finally, in the main Task Scheduler window, select the action (named runcron here) and then press the Run button to run the PHP script (see Figure 9).
  10. ?
    Figure 9. Running the New Task: You can test your new task in the main Task Scheduler window by pressing the Run button (circled in the figure).

If everything worked, you should see the task result in the logs directory. That completes the process for Vista. It’s a lot easier in Windows XP, as you’ll see next.

Running PHP Crons in Windows XP
Here’s the equivalent Windows XP process to schedule a cron:

  1. Launch Scheduled Tasks from Start ( All Programs ( Accessories ( System Tools ( Scheduled Tasks.
  2. Right-click on “Add Scheduled Task,” and select the Open option from the context menu (see Figure 10, left). Click the Next button (see Figure 10, right).
  3. ?
    Figure 10. Initializing a Task in Windows XP: Fewer options makes it simpler to create tasks in Windows XP.

  4. In the window that appears, click the Browse button and navigate to the cron.bat file. Press the Open button to select when to run the script (see Figure 11). After selecting the script frequency, press Next to continue.
  5. ?
    Figure 11. Windows XP Task Settings: Enter a name for the task, and select when the task should run.

  6. The next window lets you select the time, date, and frequency for the task (see Figure 12). Press the Next button to continue.
  7. ?
    Figure 12. Windows XP Task Settings: Enter a name for the task, and select when the task should run.

  8. Finally, specify the name and the password of the user account under which the task should execute, and then press Next (see Figure 13).
  9. ?
    Figure 13. Enter Account: Enter the account name and password under which the task should run.
    ?
    Figure 14. Task Scheduled: You’ll see this screen when you’ve successfully scheduled the task.

  10. You’ll see a review of your cron configuration (use the Back button to adjust the selected parameters). If everything is OK, press Finish (see Figure 14).
?
Figure 15. Completed Task: The completed task appears in the Scheduled Tasks list. To run the task, right-click on it, and select Run.

Author’s Note: If you want to have access to more detailed configurations, select the “Open advanced properties?” checkbox from Figure 15 before pressing the Finish button.

When you click Finish, XP creates the cron, and you should see it in the Scheduled Tasks list as shown in Figure 15. To test it, right-click it and select Run from the context menu. From this menu you also may delete/rename a cron and access its properties.

Running PHP scripts as cron tasks is a simple and elegant solution when you need to control the infrastructure and environment of your web sites. Crons can save you from the repetitive, time-consuming, and boring task of monitoring and executing activities. Executing them at low-traffic periods times will generate great results.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS