This article mainly introduces the principle and implementation method of the PHP script daemon process. It analyzes the implementation ideas, principles, formats and specific implementation methods of the PHP script daemon process in more detail. Friends in need can refer to it
Idea:
1. While loop, if there is currently no data to operate, you can sleep;
2. The crontab script executes the script every fixed period of time. First check whether it is already being executed. If not, skip it.
3. nohup background execution
4. flock -xn lock
Example:
Code to be executed: index. php
<?php set_time_limit(0); //死循环 while(1) { $message = '1111111' . "\n"; error_log($message); sleep(5); }
#/tmp/lock/test1.lock 为当前进程要锁定的文件,不同的进程配置不同的锁文件,该文件会自动创建 * * * * * flock -xn /tmp/lock/test1.lock -c 'nohup php index.php >> /php/test.log 2>&1 &' * * * * * flock -xn /tmp/mytest.lock -c 'php /home/fdipzone/php/test.php >> /home/fdipzone/php/test.log'
is writing the php script. To prevent daemon process memory overflow, it is recommended to regularly check memory usage.
Put the following code into the business script:
if(memory_get_usage()>100*1024*1024){ exit('内存溢出');//大于100M内存退出程序,防止内存泄漏被系统杀死导致任务终端 }
Note:
nohup Task viewing and closing methods:
Close:
//方法一: ps -e | grep commend kill -9 pid //方法二: fg %n //n为jobs命令查看的进程号
View:
//查看后台进程 jobs
Principle:
Use linux flock file lock to implement task locking and resolve conflicts
Format:
flock [-sxun][-w #] fd# flock [-sxon][-w #] file [-c] command
Options
-s, --shared: Obtain a shared lock
-x, --exclusive: Obtain an exclusive lock
-u, --unlock: Remove a lock, which is usually unnecessary. The lock will be automatically discarded after the script is executed
-n, -- nonblock: If the lock is not obtained immediately, fail directly instead of waiting
-w, --timeout: If the lock is not obtained immediately, wait for the specified time
-o, --close: Description of closing the file before running the command symbol. Used to control the locking process if the command spawns a child process
-c, --command: Run a separate command in the shell
-h, --help Display help
-V, - -version: Display version
Run a php file. The file lock uses an exclusive lock. If it is locked, it will fail without waiting. The parameters are -xn
* * * * * flock -xn /tmp/mytest.lock -c 'php /home/fdipzone/php/test.php >> /home/fdipzone/ php/test.log'
In this way, when the task is not completed and the next task determines that /tmp/mytest.lock is locked, the current task will be ended and the judgment will be made again in the next cycle.
PHP implementationScriptAsynchronous execution method
##php-fpm service startupScriptDetailed steps
phpScriptUpdate product list regularly
The above is the detailed content of Principles and methods of php script daemon process. For more information, please follow other related articles on the PHP Chinese website!