views:

121

answers:

4

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?

Cheers.

+7  A: 

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.

codaddict
The only thing I could think about too, unless one is using php for other things than having it on a webserver.
Frank
More generally: *request throttling*, both incoming and outgoing.
deceze
+2  A: 

Here's a snippet of how I use sleep in one of my projects:

foreach($addresses as $address)
{
  $url = "http://maps.google.com/maps/geo?q={$address}&output=json...etc...";
  $result = file_get_contents($url);
  $geo = json_decode($result, TRUE);

  // Do stuff with $geo

  sleep(1);
}

In this case sleep helps me prevent being blocked by Google maps, because I am sending too many requests to the server.

Edit: this is an example of what codaddict is saying.

captaintokyo
+1  A: 

You can use sleep to pause the script execution... for example to delay an AJAX call by server side or implement an observer. You can also use it to simulate delays.

I use that also to delay sendmail() & co. .

Somebody uses use sleep() to prevent DoS and login brutefoces, I do not agree 'cause in this you need to add some checks to prevent the user from running multiple times.

Check also usleep.

Fabio M.
+1  A: 

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.

Andy Lester
+1 thanks for that - seems like a good idea.
alex