In addition to compiling WEB service programs, php can also write some background scripts to process Background tasks and use crontab to call and execute tasks at regular intervals. However, it is not suitable to use crontab if you need to process some tasks in real time. This document describes how to use php to develop daemon. Why use php? I personally think it is mainly convenient and rich tool library support
In addition to compiling WEB service programs, php can also write some background scripts to process Background tasks and use crontab to call and execute tasks at regular intervals. However, it is not suitable to use crontab if you need to process some tasks in real time. This document describes how to use php to develop daemon. Why use php? I personally think it is mainly convenient and rich tool library support
In addition to compiling WEB service programs, php can also write some background scripts to process Background tasks and use crontab to call and execute tasks at regular intervals. However, it is not suitable to use crontab if you need to process some tasks in real time. This document describes how to use php to develop daemon.
Why use php? I personally think it is mainly convenient. The rich tool Library supports several lines of code to process some background data. For some non-demanding performance requirements, you can use php to write a daemon, which can meet most of the requirements.
Idea & method: to use php to write a daemon, you must first prevent memory problems, write the WEB Logic, and the processing of a request is complete. The memory used by the executed php script will be recycled, the background program must be running all the time, and the memory issue should be noted. A simple solution is that the master process is mainly responsible for obtaining tasks, allocating sub-processes for processing, killing sub-processes and exiting resources.
Run: Use nohup or screen to run the command. PS: the master process also needs to handle some exceptions, otherwise it may be interrupted and exited.
Example:
0) {echo "pcntl_waitpid pid :". $ pid. PHP_EOL; $ num_of_child -- ;}} pcntl_signal (SIGCHLD, 'sigchld _ handler'); while (true) {// obtain task data (such as reading from db or redis queues ), at the same time, you can control the number of sub-processes under $ num_of_child echo "parent: number of child is ". $ num_of_child. PHP_EOL; $ job_info = 'Hello world'; sleep (1); $ pid = pcntl_fork (); if ($ pid> 0) {$ num_of_child ++ ;} else if ($ pid = 0) {// subprocess, perform some task processing sleep (1); echo "child: get job \ "". $ Job_info. "\" ". PHP_EOL; exit (0);} else {echo" pcntl_fork error ". PHP_EOL ;}}?>
Original article address: Use php to develop a daemon. Thank you for sharing it.