定时器不执行

刘佳
<?php
    use \GatewayWorker\Lib\Gateway;
    use \GatewayWorker\Lib\Db;
    use Workerman\Lib\Timer;
    use Workerman\Worker;

    $task = new Worker();
    $task->name = 'task';
    // 开启多少个进程运行定时任务,注意多进程并发问题
    $task->count = 2;
    $task->onWorkerStart = function($task)
    {

        Timer::add(3, function()
        {
            echo 'close';
            $port = ****;
            $ip = "**_.**_.**_.**_";
            $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
            socket_close($socket);

        });
        getdata();
    };
    function getdata()
    {
        error_reporting(E_ALL);
        set_time_limit(0);
        $port = ****;
            $ip = "**_.**_.**_.**_";
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($socket < 0) {
            echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
        }else {
            echo "OK.\n";
        }
        $result = socket_connect($socket, $ip, $port);
        if ($result < 0) {
            echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
        }else {
            echo "连接OK\n";
        }
        $sendStr = "24 40 24 40 00 01 01";
        $sendStrArray = str_split(str_replace(' ', '', $sendStr), 2);  // 将16进制数据转换成两个一组的数组
        $s1="";
        for ($j = 0; $j < count($sendStrArray); $j++) {
            $s1.=chr(hexdec($sendStrArray));
        }
        socket_write($socket, $s1);
        $receiveStr = "";
        while($receiveStr = socket_read($socket, 8192)) {
            $receiveStrHex = bin2hex($receiveStr);  // 将2进制数据转换成16进制
            $param=analysis($receiveStrHex);
            if(!empty($param)){
                $info=Db::instance('zhongjianjian')->row("select id from ly_bus where busid=".$param);

                if($info>0){
                    Db::instance('zhongjianjian')->update('ly_bus')->cols($param)->where("id=".$info)->query();
                    //echo $param;
                }else{

                    $s=Db::instance('zhongjianjian')->insert("ly_bus")->cols($param)->query();
                    //echo $param;
                }
            }
        }
        sleep(60);
        echo date('Y-m-d H:i:s').'reload/n';
        getdata();
    }

如果在onWorkerStart 里边只设置定时器,定时器能正常执行 加上了getdata()方法定时器就不执行了 是因为只开了一个进程吗

阅读 2544
2个回答

stephen

你的 getdata 没有在 Timer::add 的匿名函数里面,而是加在 onWorkerStart 里,怎么会执行

  • 刘佳 2017-09-06

    getdata()执行了啊 定时器不执行

  • stephen 2017-09-06

    @2552: 在getdata里面调用getdata,阻塞了,单独起一个进程吧

智佳思远

定时器是在当前进程执行的,你的定时器里调用getdata(),getdata()里又调用getdata(),死循环了。当前进程被你死循环了,所以其它代码包括workerman的定时器无法被执行到。

  • 暂无评论