轮询机制php,PHP轮询(EventLoop)
PHP代码是由上往下执⾏, 很多时候php都是在等获取完数据。⽐如 执⾏过程中我们可能要等获取完远程的数据,⼜或者执⾏完⼀个复杂的sql查询,反正都是在等。难道就不能在程序等待的时候⼲点别的事情吗?
如果你有写过JS,你可能会想到回调和DOM事件。另外还可能想到php中也有回调,但处理回调的⽅式可能不⼤⼀样。下⾯,我们将来讨论下event loop如何⼯作的,还有怎么在PHP中使⽤event loop。
⼀、什么是轮询(Event Loop)
⾸先,扫下盲,轮询也称为事件循环,具体解释可以猛击这⾥
为了更好去理解轮询,我们来看下在浏览器中怎么使⽤js代码实现的:
setTimeout(function() {
console.log("inside the timeout");
}, 1);
console.log("outside the timeout");
chrome浏览器控制器中,我们可以看到先打印outside the timeout,然后打印inside the timeout。
然后, 我们勉强使⽤php来模拟js中的setTimeout,其代码如下:
function setTimeout(callable $callback, $delay) {
$now = microtime(true);
while (true) {
if (microtime(true) - $now > $delay) {
$callback();
return;
}
}
}
setTimeout(function() {
print "inside the timeout";
}, 1);
print "outside the timeout";
>
显然,php中的输出顺序是:
inside the timeout
outside the timeout
⼆、PHP中的轮询
在PHP中,我们可以使⽤类库Icicle来实现,代码如:
use Icicle\Loop;php如何运行代码
Loop\timer(0.1, function() {
print "inside timer";
});
print "outside timer";
Loop\run();
或者使⽤类库React来实现:
$loop = React\EventLoop\Factory::create();
$loop->addTimer(0.1, function () {
print "inside timer";
});
print "outside timer";
$loop->run();
友情提醒:以上需要php版本v5.5及以上,还要安装composer 参考资料
javascript事件轮询(event loop)详解
理解Node.js的事件循环(Event Loop)和线程池
PHP轮询类库:reactphp
PHP轮询类库:icicle.io