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, sent as an argument to this function.
PHP sleep() accepts only one and mandatory argument denoting the period of time, for which, 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.
Some languages like Javascript, do not have direct functions like sleep, people might obtain sleep operation by using a loop, XMLHTTP request and etc. And sometimes, people who are new to PHP may also use PHP loops for holding program execution for a while, with the required amount of time in seconds.
This will be done by a lot of work, like, using date/time functions for getting the current time stamps and manipulating them to set a limit for running loops to let the program wait for loop execution and thereby simulating sleep().
Let us have a PHP example program with the sleep() function pausing execution with the 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 the PHP random number generator, rand() function, for randomly selecting a 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 a randomly selected period of time, we have printed 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 that deal with the operations of pausing PHP program execution. These differ from the 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 the point should be kept in mind on writing PHP sleep programs. These points 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