PHP Component August 03, 2009

Easy Daemons in PHP

This class and script makes it easy to turn a one-shot php script into a daemon that runs in the background on a timer. This is good for things you want to happen infrequently. For example, your site may need to use curl to fetch several different rss feeds, combining them into one feed. You don’t want to fetch all the feeds every time someone asks for the combined one. It is better to generate the combined feed every 5 minutes or so.

Daemon source files

daemon generate_feed.php start
daemon generate_feed.php stop     
daemon generate_feed.php restart

generate_feed.php might look like this

require_once("BlogDatabase.php");
echo "Generating Feed"; // this will go to the log  

$data = new BlogDatabase();
$posts = $data->getAllNewPosts();

foreach($posts as $post)
{
    // generate an rss feed
}                          

file_put_contents("feed.xml", $contents);

Alternatives

  • crontab - This is the easiest way to get a script to run on a timer, but there are a few disadvantages. Specifically, you don’t have exact control over the timer, nor can you prevent the script from running if the system isn’t ready. Refer to this article for more information.

  • System_Daemon - This was built using System_Daemon. I created this because my daemons were behaving strangely. Our database calls weren’t working properly, and things were just generally messed up.

What it does

This uses the pear System_Daemon to create a daemon that runs your script every 5 seconds (by default). It uses shell_exec to run it, giving you the following advantages.

  • Your script runs in a “sandboxed” environment. You don’t have to worry about stale variables or strange processes making your code behave strangely.

  • You can test your script by running it on the command-line, since this is exactly what the daemon does.

  • You can easily start and stop the daemon using the included tool.

  • It puts output from the script into the daemon’s log (/var/log/generate_feed.log on my system)

Sorry it isn’t more flexible right now, but the timer can be easily changed in Daemon.php

Installation

You need to install the pear System_Daemon module. Refer to this article for instructions.

Put your daemons in the same folder as these scripts, or else make sure Daemon.php is in your include path when you run daemon from the command line.


Your comment was added successfully
Your comment could not be added

Leave a comment