draj840143 2013-07-27 23:58 采纳率: 100%
浏览 227

如果在PHP中超时,请重试curl请求?

Is there a way to retry a curl request in php after it fails, I want it to retry about 5 times if it times out but I'm not sure how to do this. Should I use curl_errno($ch) to check if it's a time-out then run a whole new curl request, or is there an easier way to do it?

  • 写回答

1条回答 默认 最新

  • douhu2370 2013-07-28 02:57
    关注

    cURL has pre-defined error codes, you can find them here: http://curl.haxx.se/libcurl/c/libcurl-errors.html The one we're after is 28, for CURLE_OPERATION_TIMEDOUT. It should be returned numerically on curl_errno, so we can use the 28 comparison to check for timeouts.

    I'd suggest you loop through until you don't get the 28, you can do this with while and also add an and to reach the limit, like this

    $limit  =   0;
    while((curl_errno($ch) == 28 or $limit == 0) and $limit < 5){
        $limit++;
        // Run curl stuff
    }
    

    You should of course add your curl fetches in the loop too. So yes, I think you need to run the curl command again. I would also recommend placing a sleep before retrying to something like after the $limit++; line adding

    if($limit > 0) sleep(1);
    

    I am assuming this will be used on the CLI so sleeps shouldn't be a problem. You just don't want to hammer a HTTP server, you may not know its firewall rules and such

    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比