An overview of the implementation and optimization of PHP program level daemons

  • 2020-06-01 09:13:52
  • OfStack

The first thing to explain is what a daemon is.

Daemons are processes that run directly in background 1. For example, we started httpd,mysqld and other processes are resident in memory running programs.

Based on demand analysis:

Requirement: there is a resident queue messageQueue (assuming it is in redis memory), and this queue may have requests to add elements to the queue from time to time. At the same time, we require that when there are elements in the queue, the element pop should be taken out in the queue order and processed (assuming that the processing is only echo 'test');

Solutions:

Now let's say I have two functions

function oPopMessageQueue () {... } // get the last element of the queue;

function vDealElement ($element) {... } processing elements;

Write a daemon to complete the above requirements.

Application:

Okay, so this is an easy one to think about, and you can do it using the while loop


while(true)
{
    if( $element  = oPopMessageQueue())
    {
        vDealElement($element);
    }  
}

Consideration 1: this program can already meet the above requirements if 1 runs straight.

However, consider that :1 running with php may cause the process to fail due to various conditions (such as running for too long), so the program cannot automatically reconnect.

Method: use cron

We run one process every 10 minutes in a timing script.

The program is then set to run for 10 minutes, which is automatically cancelled, and the code becomes


while(true)
{
    if($element = oPopMessageQueue())
    {
        vCheckTimeLimit();
        vDealElement($elemnt);
    }
}

$timeStart = 0;
function vCheckTimeLimit()
{
    global $timeStart;
    if(empty($timeStart))
    {
        $timeStart = time();
    }  

    if(time() - $timeStart > 60*10)
    {
        exit;
    }
}

Consider 2: there may be a need for the ability to pause a script at any time:

Consider using files to add pause

while(true)
{
    if($element = oPopMessageQueue())
    {
        vCheckTimeLimit();
        vCheckEnd();
        vDealElement($elemnt);
    }
}

 
function vCheckEnd()
{
    if(file_exists("/home/JesephYe/end"))
    {
        exit;
    }
}

Consider 3, can we change it to a multithreaded program to make it run more efficiently?

This is just a matter of changing cron's limit of 1 process per 10 minutes to 1 process per 1 minute

This ensures that there are 10 threads running the program

But there is one basic requirement: oPopMessageQueue() is an atomic operation


Related articles: