Search code examples
phpcurlgoutte

Sleep never continues execution


I have made a script that checks a server's availability.

The site was down and I was awaiting a fix(I was on call for a client and was awaiting a ticket from the provider), to limit calls I have used sleep():

$client = new \GuzzleHttp\Client();
$available = false;
date_default_timezone_set('doesntMatter');
//The server was more likely to respond after 5 AM, hence the decrese between intervals
$hours = array( //Minutes between calls based on current hour
  0=>30,
  1=>30,
  2=>30,
  3=>30,
  4=>20,
  5=>20,
  6=>10,
  7=>10,
  8=>10
);
$lastResponse = null;
while(!$available) {
    $time = time();
    $hour = date('G', $time);
    echo "\n Current hour ".$hour;
    try {
        $crawler = $client->request('GET', 'www.someSiteToCheck.com');
        $available = true;  //When the server returns a stus code of 200 available is set to TRUE
    } catch (\GuzzleHttp\Exception\ServerException $e) {}
    if(!$available) {
        $secondsToSleep = $hours[$hour]*60;
        echo "\n Sleeping for ".$secondsToSleep;
        sleep($hours[$hour]*$secondsToSleep); //Sleep until the next request
    } else {
        exec('start ringtone.mp3'); //Blast my stereo to wake me up
    }
}

Problem:

When I started the script it went in a 1800 second sleep and froze, it didn't re-execute anything

Given:

  1. I tested my script with a sleep of 160 (for ex) and it made multiple calls
  2. Checked my power settings so that the machine wouldn't go in stand-by
  3. Checked error logs
  4. (Even if obvious) I ran in CLI
  5. Checked sleep() documentation for issues but nothing
  6. Couldn't find anithing related

Solution

  • I think you have an error in your logic. For example: When it's 5AM Then $secondsToSleep is 20*60 = 1200sec; When you call the sleep function you multiply it again with 20 sleep($hours[$hour]*$secondsToSleep); => sleep(20*1200); => 24000sec => 6,66... hours