4.11 Pausing script execution: sleep() and usleep()This is NOT the latest copy of this book; click here for the latest version.
void sleep ( int seconds)
void usleep ( int micro_seconds)
When you want to pause execution in your script, there are two ways you can implement the code. Some people (thankfully very few) choose the first option and write code like this:
<?php
$now = time();
while ($now + 4 > time()) {
// do nothing
}
echo "Done.\n"; ?>
While it does work, there are two problems with it. Firstly, time() has a very low precision, only returning the number of whole seconds that have passed, which makes the whole thing quite vague. Secondly, PHP has to sit there looping thousands of times while it waits, essentially doing nothing. A much better solution is to use the one of the two script sleep functions, sleep() and usleep(), which take the amount of time to pause execution as their only parameter.
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. Using either of them is far more accurate than the previous time() loop, and they both have their advantages - sleep() is better if you do not need the accuracy, and usleep() is better if you do. Simple, really!
The above script could be rewritten like this:
<?php
sleep(4);
echo "Done\n"; ?>
Or this:
<?php
usleep(4000000);
echo "Done\n"; ?>
Note that the default maximum script execution time is 30 seconds, but you can use sleep() and usleep() to make your scripts go on for longer than that because technically PHP does not have control during the sleep operation.
Author's Note: PHP 5 rocks, I know, but not everyone uses it yet, and neither will they for some considerable time. The use of usleep() is a big no-no if you want backwards compatibility, because it wasn't available on Windows prior to PHP 5.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|