http如何卡住输出?

phperfan

我现在在做一个贩卖机后台的项目,坑爹的是贩卖机的传输协议是http轮询。
然后我做了以下处理

//...............

$redis = new redis();
$count = 0;
$loop = 2;
$res = [];
while($count < 60 && empty($res){    //轮询业务处理
        if(empty($res)){
                $key = 'goodsUpdate_112233';
                if($id = $redis->lpop($key)){     //查询redis队列是否有需要出货的订单
                        $sale_model = new SaleModel();
                        $res = $sale_model->Shipment($id,$machine);      //查询生成出货通知
                }
        }

        /**
         * 其他业务处理
         * .................
         **/

        if(empty($res)){
                sleep($loop);
                $count += $loop;
        )
}

//..................

Http::header('Content-Type:application/json; charset=utf-8');
$connection->send(json_encode($res,JSON_UNESCAPED_UNICODE));

但是当运行的时候,查询状态出现如下的状态

我想问问用了sleep()是不是进程线程就是处于无法使用状态?
有没有其他的办法处理这种需求?

1827 2 0
2个回答

walkor

sleep之后进程就完全sleep不会做事情了,所以不能用sleep。
可以用定时器代替sleep

phperfan
public function onMessage($connection, $data)
{
    $redis = new Redis();
    $time_interval = 2;
    //设置轮询定时器
    $timer_id = Timer::add($time_interval, function() use ($redis,$connection,&$timer_id){
        echo "------------ \n";
        echo "定时器执行 {$connection->id} \n";
        $key = 'Sea_1';
        if($value = $redis->lpop($key)){
            $connection->send($value);
            Timer::del($timer_id);
            echo "删除定时器 \n";
        }else{
            echo "未找到数据";
        }
    });
    //一次性定时器, 删除轮询定时器
    Timer::add(60,function ($timer_id,$connection){
        Timer::del($timer_id);
        $connection->send("没有数据");
    },,false);

    return true;
    $connection->send('haha');

}
  • 暂无评论
年代过于久远,无法发表回答
🔝