Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference among sleep() and usleep() in PHP

Tags:

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";  } ?> 
like image 504
MaxEcho Avatar asked Oct 24 '13 05:10

MaxEcho


People also ask

What is the difference between Usleep and sleep?

The difference between sleep() and usleep() is that sleep() takes a number of seconds as its parameter, whereas usleep() takes a number of microseconds - millionths of a second - as its parameter.

What is the use of Usleep?

The function usleep() is a C API that suspends the current process for the number of microseconds passed to it. It can be used for delaying a job. DLYJOB works well if you are looking to delay a job for more than a second. If you need to delay the job for less than a second, however, you must use the usleep() API.

What is the use of sleep in PHP?

The sleep() function delays execution of the current script for a specified number of seconds. Note: This function throws an error if the specified number of seconds is negative.

How do I pause a PHP script?

The sleep() function in PHP is an inbuilt function which is used to delay the execution of the current script for a specified number of seconds. The sleep( ) function accepts seconds as a parameter and returns TRUE on success or FALSE on failure.


2 Answers

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.

like image 61
Barmar Avatar answered Oct 06 '22 16:10

Barmar


sleep() allows your code to sleep in seconds.

  • sleep(5); // sleeps for 5 seconds

usleep() allows your code with respect to microseconds.

  • usleep(2500000); // sleeps for 2.5 seconds
like image 37
Ashwin Avatar answered Oct 06 '22 16:10

Ashwin