Pausing script execution

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.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Executing external programs >>

Previous chapter: Extension functions

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.