Like other languages, PHP sleep() is also used to pause program execution for a particular amount of time. This sleeping time could be controlled by a parameter, sending as an argument to this function.
PHP sleep() accepts only one and mandatory argument denoting the period of time, for what, the PHP code execution invoking this function, should be paused. This parameter should be in integer data type. And this integer value specifies the number of seconds to be passed, while putting the program execution into sleep.
Let us have a PHP example program with sleep() function pausing execution with specified amount of time.
<?php $sleep_time = rand(5,10); echo "<b>Putting into sleep at</b>: " . date("H:i:s") . "<br/>"; sleep($sleep_time); echo "<b>waked up after $sleep_time seconds. Current Time is: </b>" . date("H:i:s") . "<br/>"; ?>
In the above program, we have used PHP random number generator, rand() function, for randomly selecting number of seconds, the program to be put into sleep. For that, the range is specified from 5 to 10 seconds with rand().
Before invoking sleep with randomly selected period of time, we have print the time and repeat the same, after sleep is done. The program will display time in (Hour:Minute:Seconds) format, before and after sleep() function, and also, it will display how many seconds the program is paused using sleep(). And the output will be as shown below.
Putting into sleep at: 16:09:02 waked up after 5 seconds. Current Time is: 16:09:07
There are three other functions deals with the operations of pausing PHP program execution. These are differed from sleep() function with respect to the unit of time with which the parameter of these functions is passed.
These functions are listed below.
The following list of point should be kept in mind on writing PHP sleep programs. These point are used to be aware of any failure or warning notice, that may cause, while invoking PHP sleep functions.
Warning: sleep(): Number of seconds must be greater than or equal to 0
Warning: sleep() expects parameter 1 to be long
This PHP code tutorial was published on August 23, 2013.