Home >Backend Development >PHP Tutorial >Overview of the implementation and optimization of PHP program-level daemon_PHP tutorial
The first thing that needs to be explained is what a daemon is.
A daemon process is a process that always runs in the background. For example, the processes we start, such as httpd and mysqld, are all programs running in resident memory.
Analyze needs:
Requirement: There is a resident queue messageQueue (assumed to be in redis memory). 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 elements are popped out according to the queue order and processed (assuming that this processing is just echo 'test');
Solution:
Now assume there are two functions
function oPopMessageQueue(){ …} //Get the last element of the queue;
function vDealElement($element) { …} handles elements;
Required to write a daemon to complete the above requirements.
Program:
Okay, this program is easy to think of. You can use a while loop to do it
However, consider: 1. Running the php process may cause the process to hang due to various circumstances (such as running for too long), so that the program cannot automatically reconnect.
Method: Use cron
We start a process in the timed script to run this program every 10 minutes.
Then set the running time of this program to 10 minutes, and automatically cancel it after 10 minutes, so the code becomes