当前位置: 代码迷 >> 综合 >> swoole_server-defer
  详细解决方案

swoole_server-defer

热度:123   发布时间:2023-10-20 08:21:59.0

简介

延后执行一个PHP函数。Swoole底层会在EventLoop循环完成后执行此函数。此函数的目的是为了让一些PHP代码延后执行,程序优先处理IO事件。底层不保证defer的函数会立即执行,如果是系统关键逻辑,需要尽快执行,请使用after定时器实现。

https://wiki.swoole.com/wiki/page/516.html

使用实例

function query($server, $db) {
    $server->defer(function() use ($db) {
    $db->close();});
}

注意事项

Server

<?php class Server {
     private $serv;public function __construct(){
     $this->serv = new swoole_server('127.0.0.1', 9501);//注意这里要用多进程模式,不填写默认是多进程$this->serv->set(array('worker_num' => 4,'daemonize' => false,'backlog' => 128,));$this -> query($this->serv);$this->serv->on('Connect', array($this,'onConnect'));$this->serv->on('Receive', array($this,'onReceive'));$this->serv->on('Close', array($this,'onClose'));$this->serv->start();}public function onConnect(swoole_server $server, int $fd, int $reactorId){
     //只能写在回调函数中$server->defer(function() use ($server) {
     print_r("我执行了");}); print_r($fd."--连接上了\n"); }public function onReceive(swoole_server $server, int $fd, int $reactor_id, string $data){
     print_r("主进程\n");$server->after(5000,function() use ($server,$fd){
     $server->send($fd, "我是after");});}public function onClose(swoole_server $server, int $fd, int $reactorId){
     print_r($fd."--关闭了连接\n");}function query($server) {
     } }new Server();

Client

<?php $client = new swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, -1))
{exit("connect failed. Error: {
    $client->errCode}\n");
}
$client->send("我是发送的数据\n");while (true) {$as = $client->recv();print_r($as."\n");
}

结果

swoole_server-defer

参考地址

https://wiki.swoole.com/wiki/page/516.html