Creating a Daemon Process in PHP

In our previous PHP tutorial, we have explained how use Prepared Statement with PHP and MySQL. In this tutorial we will explain how to create Daemon script in PHP.

PHP is a server side language primarily used for developing web applications, but it can also be used as a background script for many purposes like sending notifications, message retrieval, analyzing data, database clean up etc.

So here in this tutorial, we will explain what is Daemon process, advantages of Daemon process over cron script and how to create Daemon process in PHP.

Also, read:

1. What is Daemon Process

Daemon is a program that runs in the background without requiring any user interaction. It’s totally different that the normal PHP scripts as there are no direct of a user. As the normal script runs on web server and output rendered on web pages, the daemon scripts are executed at background from the command line PHP interpreter without interacting with the web server.


2. Why Use Daemon Process

Both the Cron and Daemon script are useful and used to run scheduled tasks. The cron scripts are useful when we need to run a task once in a while. But if your task needs to run more than a few times per hour you probably want to run a Daemon as it always runs. There are following benefit of using Daemon.

  • The Daemon process always runs automatically.
  • Daemon process can run at frequencies greater than 1 per minute.
  • It can remember state from its previous run more easily, which makes programming simpler and can improve efficiency in some cases.
  • Avoid memory leaks problems.

3. How To Write Daemon in PHP

As the Daemon process run always, so the Daemon scripts are written in way to iterate itself with while(true) and never stop.

Here is the basic example of Daemon script that’s always running and print current date time in every 60 seconds. In this example, you will see the two basic elements of Daemon. The first one is infinite loop while(true) and other one is sleep() statement. The while loop with true lets the script to run infinitely and sleep statement set the script execution interval to not use 100% of the CPU all the time.

<?php

set_time_limit(0);

$sleepTime = 60;

while (TRUE) {

  sleep($sleepTime);
   
  echo 'Current time is : ' . date('Y-m-d H:i:s');
  
}

?>

The above script can not be run via web server as in this case the server need to wait until a timeout. So this needs to execute from command line PHP interpreter and it will print current date time on console in every 60 seconds.

In this tutorial, we have explained how to create basic Daemon process using PHP. You can enhance this basic example to use as per your requirement like sending notifications, analyzing data etc.


You may also like:

One thought on “Creating a Daemon Process in PHP

  1. Can you explain why don’t we need PHP’s ignore_user_abort () in the daemon creation script?

Comments are closed.