您确实需要运行 PHP 守护程序才能有效地执行此操作(并且需要是 PHP 5.3)。我写了一个相当完整的使用概述用于守护进程的 PHP https://stackoverflow.com/questions/4169412/how-to-design-a-daemon-with-a-mysql-db-connection/4169523#4169523。无论您选择什么,我都建议您使用基于事件的运行循环系统。
我设计了一个基本的 RunLoop 库,名为LooPHP https://github.com/Wordi/LooPHP这可能会有所帮助,特别是如果您要处理*_select
。我非常乐意回答您对此的任何问题。
EDIT:
在基于事件的系统中,您不只是while
命令列表,您对侦听器做出反应。例如...
而不是做:
while( 1 ) {
... /* listen, react */
} /* repeat */
运行循环通过注册侦听器(套接字和其他异步事件生成器)来工作
class ReactClass { ... }
$loop = new LooPHP_EventLoop( new ReactClass );
//add one time event
$loop->addEvent( function() {
print "This event was called 0.5 second after being added\n";
}, 0.5 /* in seconds */ );
//this creates a repeating event, this is called right away and repeats
$add_event = function() use ( $loop, &$add_event ) {
print "This event is REPEATEDLY called 0.1 every second\n";
$loop->addEvent( $add_event, 0.1 );
};
$add_event();
//start the loop processing, no events are processed until this is done
$loop->run(); //php doesn't leave this call until the daemon is done
exit(0); //cleanly exit
上面的例子是一个非常简单的 1 源 EventLoop 和一个手动添加定时函数(甚至可以在调用中添加这些函数)ReactClass
).
在我正在工作的应用程序中,我需要将异步事件馈送到后端(通过套接字),然后需要能够调用与原始事件任意偏移的函数(对于超时的客户端等)。
如果您想要更多示例,可以在以下位置找到它们github https://github.com/Wordi/LooPHP/blob/master/examples/.
希望这个对你有帮助。