What is a practical use for PHP's sleep()?

前端 未结 13 2678
时光说笑
时光说笑 2020-12-23 19:17

I just had a look at the docs on sleep().

Where would you use this function?

Is it there to give the CPU a break in an expensive function?

Any common

13条回答
  •  旧巷少年郎
    2020-12-23 20:17

    Super old posts, but I thought I would comment as well. I recently had to check for a VERY long running process that created some files. So I made a function that iterates over a cURL function. If the file I'm looking for doesn't exist, I sleep the php file, and check again in a bit:

    function remoteFileExists() {
        $curl = curl_init('domain.com/file.ext');
    
        //don't fetch the actual page, you only want to check the connection is ok
        curl_setopt($curl, CURLOPT_NOBODY, true);
    
        //do request
        $result = curl_exec($curl);
    
        //if request did not fail
        if ($result !== false) {
            //if request was ok, check response code
            $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  
    
            if ($statusCode == 404) {
                  sleep(7);
                  remoteFileExists();
            }
            else{
                echo 'exists'; 
            }
        }
    
        curl_close($curl);
    
    }
    
    echo remoteFileExists();
    

提交回复
热议问题