PHP - If no results, wait and try again

房东的猫 提交于 2019-12-23 03:03:55

问题


I'm calling a web service via GET protocol and the response will either be echoed out on the page as true or false.

I'm trying to write logic that will retry up to 3 times if the web service returns false. However, the first time I want to wait 1 second, the second time I want to wait 10 seconds, and the third time I want to wait 60 seconds.

This is what I currently have. Is there a better way to achieve this?

if ($wsReturn == 'false') {
    sleep(1);
    $wsReturn = strip_tags(file_get_contents($link));

        if ($wsReturn == 'false') {
            sleep(10);
            $wsReturn = strip_tags(file_get_contents($link));

                if ($wsReturn == 'false') {
                    sleep(60);
                    $wsReturn = strip_tags(file_get_contents($link));
                }
        }
}

回答1:


Just use an array and a loop to make any number of iterations with any pause times

$i = 0;
$sleep = [1, 10, 60];

while( $wsReturn == 'false' )
{
    sleep( $sleep[$i] );

    // your logic goes here
    $wsReturn = strip_tags(file_get_contents($link));


   if( ++$i >= count($sleep) )
      break;
} 



回答2:


This is what I ended up with after @Pavel Lint sparked the idea for me:

$i = 0;
$waitTimes = array();
$waitTimes = [1, 10, 30]

while ($wsReturn == 'false') {
    sleep( $waitTimes[$i] );
    $wsReturn = strip_tags(file_get_contents($link));
    $++i

    if ($i >= count($waitTimes)-1) { break; }
}


来源:https://stackoverflow.com/questions/32031685/php-if-no-results-wait-and-try-again

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!