问题
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