Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 pitfalls?

like image 205
alex Avatar asked Oct 14 '10 06:10

alex


People also ask

Why do we use sleep in PHP?

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.

What is the difference between sleep and Usleep?

The sleep subroutine suspends the current process for whole seconds. The usleep subroutine suspends the current process in microseconds, and the nsleep subroutine suspends the current process in nanoseconds.

How do I make PHP sleep?

In order to delay program execution for a fraction of a second, use usleep() as the sleep() function expects an int. For example, sleep(0.25) will pause program execution for 0 seconds.

How do you sleep in HTML?

Sleep() With the help of Sleep() we can make a function to pause execution for a fixed amount of time. In programming languages such as C and Php we would call sleep(sec).


2 Answers

One place where it finds use is to create a delay.

Lets say you've built a crawler that uses curl/file_get_contents to get remote pages. Now you don't want to bombard the remote server with too many requests in short time. So you introduce a delay between consecutive requests.

sleep takes the argument in seconds, its friend usleep takes arguments in microseconds and is more suitable in some cases.

like image 53
codaddict Avatar answered Sep 22 '22 14:09

codaddict


Another example: You're running some sort of batch process that makes heavy use of a resource. Maybe you're walking the database of 9,000,000 book titles and updating about 10% of them. That process has to run in the middle of the day, but there are so many updates to be done that running your batch program drags the database server down to a crawl for other users.

So you modify the batch process to submit, say, 1000 updates, then sleep for 5 seconds to give the database server a chance to finish processing any requests from other users that have backed up.

like image 27
Andy Lester Avatar answered Sep 24 '22 14:09

Andy Lester