phpsleepusleep

Difference among sleep() and usleep() in PHP


Can any body explain me what is the difference among sleep() and usleep() in PHP.

I have directed to use following scripts to do chat application for long pulling but in this script I am getting same effect using usleep(25000); or without usleep(25000);

page1.php

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" 
       type="text/javascript"></script>

<script>
var lpOnComplete = function(response) {
    console.log(response);
    // do more processing
    lpStart();
};

var lpStart = function() {
    $.post('page2.php', {}, lpOnComplete, 'json');
};

$(document).ready(lpStart);
</script>

page2.php

<?php
$time = time();
while((time() - $time) < 30) {
    // query memcache, database, etc. for new data
    $data = getLatest();

    // if we have new data return it
    if(!empty($data)) {
        echo json_encode($data);
        break;
    }

    usleep(25000);
}

function getLatest() {
    sleep(2);
    return "Test Data"; 
}
?>

Solution

  • The argument to sleep is seconds, the argument to usleep is microseconds. Other than that, I think they're identical.

    sleep($n) == usleep($n * 1000000)
    

    usleep(25000) only sleeps for 0.025 seconds.