Search code examples
phpfunctionsleepusleep

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?


Solution

  • 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.