How to set a delay in php?
(PHP 4, PHP 5, PHP 7, PHP 8) Show sleep — Delay execution Descriptionsleep(int Delays the program execution for the given number of
Parametersseconds Halt time in seconds (must be greater than or equal to Return ValuesReturns zero on success. If the call was interrupted by a signal, sleep() returns a non-zero value. On Windows, this value will always be Errors/Exceptions If the
specified number of Changelog
ExamplesExample #1 sleep() example
This example will output (after 10 seconds) See Also
ash b ¶ 8 years ago
Anonymous ¶ 4 years ago
barlow at fhtsolutions dot com ¶ 11 years ago
MPHH ¶ 19 years ago
Diego Andrade ¶ 6 years ago
hartmut at six dot de ¶ 22 years ago
|
so use sleep if you have to wait for events and don't want to burn to much cycles, but don't use it for silly delayed output effects!
Anonymous ¶
8 years ago
If you are having issues with sleep() and usleep() not responding as you feel they should, take a look at session_write_close()
as noted by anonymous on comments;
"If the ajax function doesn't do session_write_close(), then your outer page will appear to hang, and opening other pages in new tabs will also stall."
ealexs at gmail dot com ¶
11 days ago
From my testing calling sleep(0); will do a `thread spin`.
It would be nice if this was to be put explicitly in the documentation as it is useful. You can do the minimum wait without overloading the CPU thread.
Anonymous ¶
1 year ago
I wrote a simple method for sleeping with a float, which also allows you to do milliseconds (via fractional seconds).
function sleepFloatSecs($secs) {
$intSecs = intval($secs);
$microSecs = ($secs - $intSecs) * 1000000;
if(
$intSecs > 0) {
sleep($intSecs);
}
if($microSecs > 0) {
usleep($microSecs);
}
}
?>
And testing on my machine it works perfectly: $x = [0.100,0.250,0.5,1.0,1.5,2.0,2.5];
foreach(
$x as $secs) {
$t = microtime(true);
sleepFloatSecs($secs);
$t = microtime(true) - $t;
echo "$secs \t => \t $t\n";
}
?>
Output: 0.1 => 0.10017800331116
0.25 => 0.25016593933105
0.5 => 0.50015211105347
1 => 1.0001430511475
1.5 => 1.5003218650818
2 => 2.000167131424
2.5 => 2.5002470016479
?>
LVT ¶
9 years ago
Always close your SQL connection and free the memory before using sleep( ) or you will be needlessly holding a SQL connection for [xx] seconds, remember that a shared hosting environment only allows max 30 SQL connections at the same time.
joshmeister at gmail dot com ¶
9 years ago
Here is a simplified way to flush output to browser before completing sleep cycle. Note the buffer must be "filled" with 4096 characters (bytes?) for ob_flush() to work before sleep() occurs.
ob_implicit_flush(true);
$buffer = str_repeat(" ", 4096);
echo "see this immediately.
";
echo $buffer;
ob_flush();
sleep(5);
echo "some time has passed";
?>
jimmy at powerzone dot dk ¶
12 years ago
Notice that sleep() delays execution for the current session, not just the script. Consider the following sample, where two computers invoke the same script from a browser, which doesn't do anything but sleep.
PC 1 [started 14:00:00]: script.php?sleep=10 // Will stop after 10 secs
PC 1 [started 14:00:03]: script.php?sleep=0 // Will stop after 7 secs
PC 2 [started 14:00:05]: script.php?sleep=0 // Will stop immediately
http://php.net/session_write_close may be used to address this problem.
Anonymous ¶
13 years ago
This will allow you to use negative values or valuer below 1 second.
(0.5); ?>
function slaap($seconds)
{
$seconds = abs($seconds);
if ($seconds < 1):
usleep($seconds*1000000);
else:
sleep($seconds);
endif;
}
?>
manu7772 at gmail dot com ¶
1 year ago
Sleep method with parameter in milliseconds :
public static function ms_sleep($milliseconds = 0) {
if($milliseconds > 0) {
$test = $milliseconds / 1000;
$seconds = floor($test);
$micro = round(($test - $seconds) * 1000000);
if($seconds > 0) sleep($seconds);
if($micro > 0) usleep($micro);
}
}
f dot schima at ccgmbh dot de ¶
12 years ago
Remember that sleep() means "Let PHP time to do some other stuff".
That means that sleep() can be interrupted by signals. That is important if you work with pcntl_signal() and friends.
toddjt78 at msn dot com ¶
12 years ago
Simple function to report the microtime since last called or the microtime since first called.
function stopWatch($total = false,$reset = true){
global $first_called;
global $last_called;
$now_time = microtime(true);
if ($last_called === null) {
$last_called = $now_time;
$first_called = $now_time;
}
if ($total) {
$time_diff = $now_time - $first_called;
} else {
$time_diff = $now_time - $last_called;
}
if ($reset)
$last_called = $now_time;
return $time_diff;
}
?>
$reset - if true, resets the last_called value to now
$total - if true, returns the time since first called otherwise returns the time since last called
code {@} ashleyhunt [dot] co [dot] uk ¶
11 years ago
A really simple, but effective way of majorly slowing down bruit force attacks on wrong password attempts.
In my example below, if the end-user gets the password correct, they get to log in at full speed, as expected. For every incorrect password attempt, the users response is delayed by 2 seconds each time; mitigating the chances of a full bruit force attack by a limit of 30 lookups a minute.
I hope this very simple approach will help make your web applications that little bit more secure.
Ashley
public function handle_login() {
if($uid = user::check_password($_REQUEST['email'], $_REQUEST['password'])) {
return self::authenticate_user($uid);
}
else {
// delay failed output by 2 seconds
// to prevent bruit force attacks
sleep(2);
return self::login_failed();
}
}
?>
LVT ¶
9 years ago
Another reason for not to abuse sleep( ) is that along with the maximum of 30 sql connections, a shared hosting environment usually limits the number of processes to 20, if your website has many users online and you put sleep( ) everywhere in the code, your server will throw a 508 error (resource limit reached) and will stop serving your website.
soulhunter1987 at post dot ru ¶
12 years ago
Since sleep() can be interrupted by signals i've made a function which can also be interrupted, but will continue sleeping after the signal arrived (and possibly was handled by callback). It's very useful when you write daemons and need sleep() function to work as long as you 'ordered', but have an ability to accept signals during sleeping.
function my_sleep($seconds)
{
$start = microtime(true);
for ($i = 1; $i <= $seconds; $i ++) {
@time_sleep_until($start + $i);
}
}
?>
smcbride at msn dot com ¶
1 year ago
An example of using sleep to run a set of functions at different intervals. This is not a replacement for multi-threading, but it could help someone that wants to do something cheap. You don't have to use eval(). It is just used as an example. This is different than running a standard 1 second sleep loop, due to sleeping longer does not consume as much CPU.
// current time
echo date('h:i:s') . "\n";// Some example functions
function function_a() { echo 'function_a called @ ' . date('h:i:s') . PHP_EOL; }
function function_b() { echo 'function_b called @ ' . date('h:i:s') . PHP_EOL; }
function function_c() { echo 'function_c called @ ' . date('h:i:s') . PHP_EOL; }// Add some timers (in seconds) with function calls
$sleeptimers = array();
$sleeptimers['5'][0]['func'] = 'function_a();';
$sleeptimers['10'][0]['func'] = 'function_b();';
$sleeptimers['15'][0]['func'] = 'function_c();';// Process the timers
while(true) {
$currenttime = time();
reset($sleeptimers);
$mintime = key($sleeptimers);
foreach($sleeptimers as $SleepTime => $Jobs) {
foreach($Jobs as $JobIndex => $JobDetail) {
if(!isset($JobDetail['lastrun'])) {
$sleeptimers[$SleepTime][$JobIndex]['lastrun'] = time();
if($SleepTime < $mintime) $mintime = $SleepTime;
} elseif(($currenttime - $JobDetail['lastrun']) >= $SleepTime) {
eval($JobDetail['func']);
$lastrun = time();
$sleeptimers[$SleepTime][$JobIndex]['lastrun'] = $lastrun;
$mysleeptime = $SleepTime - ($currenttime - $lastrun);
if($mysleeptime < 0) $mysleeptime = 0;
if(($currenttime - $JobDetail['lastrun']) < $mintime) $mintime = $mysleeptime; // account for length of time function runs
echo 'Sleep time for function ' . $JobDetail['func'] . ' = ' . $mysleeptime . PHP_EOL;
}
}
}
echo 'Sleeping for ' . $mintime . ' seconds' . PHP_EOL;
sleep($mintime);
}?>
webseos at gmail dot com ¶
14 years ago
This is a critical thing to use time delay function as sleep() Because a beginner can find that this is not working and he/she will see that all output appearing at a time.
A good way to implement this is by using the function - ob_implicit_flush() then you don't need to use flush() function explicitly.
A sample code :
ob_implicit_flush(true);
for($i=0;$i<5;$i++)
{
$dis=<<
$i
DIS;
echo $dis;sleep(5);
//flush();
}
mohd at Bahrain dot Bz ¶
12 years ago
I hope this code will help somebody to solve the problem of not being able to flush or output the buffer to the browser (I use IE7).
It may work for you with just [ echo str_repeat(".", 4096); ] and without even using ob_... and flush.
ob_start();ob_implicit_flush(true);
//[ OR ] echo "..."; ob_flush(); flush();set_time_limit(0);
function
sleep_echo($secs) {
$secs = (int) $secs;
$buffer = str_repeat(".", 4096);
//echo $buffer."\r\n
\r\n";
for ($i=0; $i<$secs; $i++) {
echo date("H:i:s", time())." (".($i+1).")"."\r\n
\r\n".$buffer."\r\n
\r\n";
ob_flush();
flush();
sleep(1);
//usleep(1000000);
}
}sleep_echo(30);ob_end_flush();
?>