by Indrek Ots

• articles

Tags

• php
• background processing
• cron
• unix
• composer
• redis
• resque

Notice! This post is more than a year old. It may be outdated.

A background job is a task that is executed “behind the scenes” and without user intervention. In a web application context, it is a task that is executed outside of the main flow. Therefore the end user has no clue of it ever happening. This is great, because you don’t want to make your users wait for a computationally heavy task to finish and then load a web page. A more elegant solution would be to load the page as soon as possible, and run the time consuming tasks, which are not required for displaying the page, in the background. In addition, a background job might not even be user initiated. These include scheduled and recurring tasks.

This series of posts covers some of the solutions for implementing a background job in PHP. Firstly, let’s look at how to create jobs that are not initiated by the user. The easiest method might be to use cron.

The software utility cron is a time-based job scheduler in Unix-like computer operating systems.

On Windows you can use the Task Scheduler but this is not going to be covered in this post.

Cron jobs

Cron is a daemon which executes commands at a specified point in time. To add a new job, let’s use the crontab editor.

This opens a text file with a list of commands meant to be run at specified times. In this first example, we’re going to add a job which prints “Hello World” to a log file in every 2 minutes. Add the following line to your crontab file and save it.

*/2 * * * * php /home/user/Desktop/hw.php >> /home/user/Desktop/hw.log


A cron job is laid out as follows: minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command. To run a script more than one time per time unit you can use the syntax described above. This runs the command every 2 minutes. For more information about cron jobs, check out this tutorial.

The contents of hw.php could simply look like this:

Now in every 2 minutes, the log file is updated with a new line. Based on this simple example, we can build a more sophisticated solution which actually does something useful for our web application. For example, the cron job could pull data from an external webservice for caching purposes.

Depending on your setup, you might run into permission issues. To avoid that, create the cron job under your webserver’s user. Apache is usually running under www-data.