首页 > 解决方案 > 为什么在代码中有睡眠时它会运行两次 API 调用???(PHP/Laravel)

问题描述

public function createall()
{

    $users = User::orderBy('id', 'ASC')
           ->where('server', 'Demo')
           ->where('enable', '1')
           ->where('mt4_account', '!=', 0)
           ->take(4)
           ->get();
    
    foreach ($users as $user) {
        $server = Server::where('Serverdesc', $user->server)->first();

        $post = [
            'server' => $server->serverdesc,
            'api_key' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
            'login' => intval($user->mt4_account),
        ];
        $datapost = json_encode($post);

// initialize cURL
        $ch = curl_init();

// set options
        curl_setopt($ch, CURLOPT_URL, "http://xxxxxxxxxxxxxxxxx/closetrades");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $datapost);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($datapost))
        );
        $result = curl_exec($ch);

        curl_close($ch);

        sleep(5);   

        $ptr = fsockopen($server->serveraddress, $server->serverport);
        // Checking errors
        if (!$ptr) {
            dump("Connection error");
            exit;
        }
        $useracc = $user->mt4_account;
        $userpass = $user->mt4_pass;

        $request = "WUSERINFO-login=" . $useracc . "|password=" . $userpass . "\nQUIT\n";
        fputs($ptr, $request);

        while (!feof($ptr)) {
            // Reading the string of symbols
            $line = fgets($ptr, 128);
            // End of result transmission flag
            if ($line == "end\r\n") {
                fclose($ptr);
                break;
            }
            // Processing
            $data = (explode(chr(9), $line));

            if (substr($data[0], 0, 4) == "Bala") {
                $balance = substr($data[0], 9, strlen($data[0]) - 11);
                dump($data, $useracc, $userpass, $balance);
            }
        }
}
}

使用代码中的 sleep 函数,它上面的 API 调用,显然只有 API 调用,对每条记录执行两次。我看到 API 在服务器的终端窗口上写出结果,所以我绝对确定它会执行两次。

我删除了 sleep 函数,API 调用为每条记录执行一次。服务器上的终端窗口显示正确的呼叫数量...

其余代码,例如转储变量的代码,仅打印一次,因此显然该部分仅执行一次...

为什么?如何?我一脸懵逼……

标签: phplaravelsleep

解决方案


推荐阅读