New Page  |  Edit Page


Daemon Process

A Daemon Process is a program that runs in the background without requiring any user interaction. It can be used for many purposes like sending notifications, message retrieval, analyzing data, database clean up, etc.

A Daemon script is different from typical PHP scripts as there is no direct user input. As a normal script runs on a web server rendereing it's output onto web pages, daemon scripts are executed in the background from the command line PHP interpreter without interacting with the web server. Just as how a Cron job is useful to run a scheduled task, a Daemon script is useful and may even be the better option as it is already continually running in the background.

The Benefits of using a Daemon Process:

Daemon scripts are written in way to iterate themselves with while(true) and never stop.

$sleepTime = 60;

while(true) {
    echo 'Current time is : ' . date('Y-m-d H:i:s');
[Dameon Script]

The above Daemon script is always running and prints the current date time every 60 seconds. In this example, there are two basic elements of Daemon. The first one is an infinite loop while(true) and other one is a sleep() statement. The while loop with true lets the script to run infinitely and the sleep statement sets the script execution interval to not use 100% of the CPU all of the time.

The script cannot be run via a web server as in as the server needs to wait until a timeout. This needs to execute from command line PHP interpreter and it will print current date time on console in every 60 seconds. This basic example can bee enhanced to send notifications, analyze data, etc.