PHP Sleep Output before putting to sleep for next step - php

I am using SLEEP(). It seems the function works, but the script waits until all my sleep() functions have ran their course before the script displays any output.
Is there a way I can get output for for 1st and then it should wait and go to next ?
echo date('h:i:s') . "<br />";
//sleep for 10 seconds
sleep(10);
//start again
echo date('h:i:s'). "<br />";
//sleep for 10 seconds
sleep(10);
//start again
echo date('h:i:s');
I need output of 1st echo and then script should wait and give second echo ....and so on

Sleep Does not matter as for as output of the page is concerned. Page is served as soon as the last sleep is done... Though it stop processing of the page on server for the time of the sleep. .. in your scenario you should be using javascript for the affect.

You see, PHP runs completely on server-side, and sleep will just make the latency of the page more severe.
As Rab has suggested, try using JavaScript instead. It's not the same as Java (in fact, a lot different), and you might like to find some good tutorials online, or get some good books (the one from Murach is really good, trust me).

Related

Uncontrollable Sleep? PHP

I understand how sleep works, But it works before something happens. Say for example I have a few echos and mail and some other things. Then have a sleep, then a redirect. Well, it looks like the sleep goes first, then everything just spam at once and cause server cpu increase. Is there something that is similar to sleep, that will not act after things have not been executed?
for example
echo 'Hey';
sleep(3);
echo 'My next text after 3 seconds is up';
well, with this, This does not work, and it does the same thing using C#.
When this happens, the page will not respond for 3 seconds, then both messages "Hey" & "My next text after 3 seconds is up" will show all at once. Is im using this for the wrong thing? Is there something else I should use?
Since I have never used sleep, and I seen alot of people use this for the same thing and it works, but in my case, it does not really works the way I thought it would.
PHP not C#
You can do it via flushing the output at points. You can also use ob_implicit_flush for this purpose which would ensure that output will be flushed at each output call without explicit calls for flush.
header( 'Content-type: text/html; charset=utf-8' );
echo 'Hey';
for($i=0;$i<60;$i++){
echo "<br />My next text after $i seconds is up";
ob_flush();
flush();
sleep(1);
}
Note that php docs for ob_flush suggests that you should try putting content-type header when things are not working. But above code worked without that also.
It runs exactly as it was programmed, the thing is, the output is being buffered. You have to disable buffering, and force a flush() to make sure its sent before the sleep().
while (# ob_end_flush()); // closes all existing buffers if any
echo 'Hey';
flush(); // make sure it was flushed to the client
sleep(3);
...
And still it might not work in all cases, because theres another buffer, and this one you cannot control: the browser. Some browsers will not render any HTML unless it has received a certain minimum amount of data.

How do I get the sleep function to respond appropriately in a for loop in PHP

I am writing a script that gets an eight digit number then reads it out loud. I want a delay of two seconds between the numbers as they are being read out. The problem is that even after setting the delay with sleep(), all my numbers are read out at once which leads to a summon-like audio that is getting me closer to being the antichrist with every debug. Here is my code. How do i get my loop to execute so that the numbers are read as e.g 2 .... 1 .... 3 .... 4 .... (where .... = 2 seconds.)
for($counter=0; $counter<count($dbId); $counter++)
{
$fileName = array_search($dbId[$counter], $letterArray);
echo "<audio src='../resources/audio/mp3/'.$fileName.'.mp3' autoplay></audio>";
echo time() . "<br />";
sleep(2);
}
You have an incorrect understanding of sleep. Sleep delays the php script, which delays the
response from the server, but the resulting webpage that you serve will be exactly the same
with or without sleep. It will just take longer to load. You can not control this from php
you have to do it on the client somehow. Look at this question for example.
PHP is a hypertext pre processor. Meaning it's output cannot be send intermittently to the browser.
You have two options.
Create all audio elements without autoplay and handle your desired functionality with javascript using setInterval
Make a series of AJAX requests in order to get the next audio element enabling the autoplay feature. These requests can be fired by either listening for the audio to finish, or again using setInterval

PHP sleep delay

In PHP, I want to put a number of second delay on each iteration of the loop.
for ($i=0; $i <= 10; $i++) {
$file_exists=file_exists($location.$filename);
if($file_exists) {
break;
}
//sleep for 3 seconds
}
How can I do this?
Use PHP sleep() function. http://php.net/manual/en/function.sleep.php
This stops execution of next loop for the given number of seconds. So something like this
for ($i=0; $i <= 10; $i++) {
$file_exists=file_exists($location.$filename);
if($file_exists) {
break;
}
sleep(3); // this should halt for 3 seconds for every loop
}
I see what you are doing... your delaying a script to constantly check for a file on the filesystem (one that is being uploaded or being written by another script I assume). This is a BAD way to do it.
Your script will run slowly. Choking the server if several users are running that script.
Your server may timeout for some users.
HDD access is a costly resource.
There are better ways to do this.
You could use Ajax. And use a timeout to call your PHP script every few seconds. This will avoid the slow script loading. And also you can keep doing it constantly (the current for loop will only run for 33 seconds and then stop).
You can use a database. In some cases database access is faster than HDD access. Especially with views and caching. The script creating the file/uploading the file can set a flag in a table (i.e. file_exists) and then you can have a script that checks that field in your database.
You can use sleep(3) which sleeps the thread for 3 seconds.
Correction sleep method in php are in seconds.
Hare are two ways to sleep php script for some period of time. When you have your code and want to pause script working for some time use these functions.
In these examples the first part of code will be done on script run and the second part of code will be done but with time delay.
Using sleep() function you can define sleep time in seconds.
Example:
echo "Message 1";
// The first part of code.
$timeInSeconds = 3;
sleep($timeInSeconds);
// The second part of code.
echo "Message 2";
This way it is possible to sleep php script for 3 seconds. Using this function you can sleep script for whole number (integer) of seconds.
Using usleep() function you can define sleep time in microseconds. This sleep time is convenient for intervals that require more precise time than one second.
Example:
echo "Message 1";
// The first part of code.
$timeInMicroSeconds = 2487147;
usleep($timeInMicroSeconds);
// The second part of code.
echo "Message 2";
You can use this function if you want to sleep php for smaller time values than second (float). In this example I have put script to sleep for 2.487147 seconds.
Have you considered using a PHP Daemon script using supervisorD. I use it in multiple tasks that are required to be running all the time.
The catch is making sure that each time you are running your script you check for memory resources. If its too high, stop the process and then let it restart itself up again.
I have successfully used this process to be always checking database records for tasks to process.
It might be overkill but worth considering.

"No data received" error when I have a mysql query in while loop

I have this PHP code:
<?php
include_once("connect_to_mysql.php");
$max=300;
while($max--)
{
sleep(1);
doMyThings();
}
?>
it is supposed to repeat a mysql query 300 times with gap of 1 second between each. But the problem is after a minute or so in the browser i get this message: No Data Received. Unable to load the webpage because the server sent no data.
The problem is the following: Your code will at least (without considering the amount of time needed by doMyThings()) last 300 seconds. Most PHP environments set the default script running time to about 60 secs, the script stops and nothing is printed out.
Next thing is (if script execution time is set high enough to allow long running scripts), the script has to run until its finished (that is, ~300 secs) and after that, data is written onto the output stream. Until there, you won't see any output.
To circumvent those two problems, see this code:
<?php
// If allowed, unlimited script execution time
set_time_limit(0);
// End output buffering
ob_end_flush();
include_once("connect_to_mysql.php");
$max=300;
// End output buffering IE and Safari Workaround
// They will only display the webpage if it's completely loaded or
// at least 5000 bytes have been "printed".
for($i=0;$i<5000;$i++)
{
echo ' ';
}
while($max > 0)
{
sleep(1);
doMyThings();
$max--;
// Manual output buffering
ob_flush();
flush();
}
?>
Maybe this post is also of interest to you: Outputting exec() ping result progressively
The browser will not wait a whole 5 minutes for you to complete your queries.
You need to find a different solution. Consider executing the PHP script in CLI.
It seems that you have a timeout executing 300 times doMyThings();
You can try with set_time_limit(0);
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini.
When you execute long time php code on server side, you need change max_execution_time directive in php.ini. But browser will not wait how long as you want so you need use async technology like AJAX

At my wits end on sleep()

I've got sleep(n) in a loop that is intended to do output on a periodic cycle.
But when I run the loop, nothing happens until all of the seconds in the intended loop duration accrue collectively, after which all of the output comes spilling out at once.
Help. Thanks.
try that:
ob_end_flush (); // just in case
while (1) {
echo 'wait for it<br/>'.PHP_EOL;
flush ();
sleep (2);
}
Maybe you need to flush() the output buffer after each piece of output?
Argh, the site's not letting me add comment to mathroc's latest. So I'll put it here:
It didn't work for me. But the following is really weird: I accidentally stumbled upon some other sleep code on the web that I stuck in front of what I've got:
<HTML>
<BODY>
$c=0;
while($c <$chunks){
$rand = rand(2000000, 6000000);
echo '<br> . . . sleeping for ' . round(($rand / 1000000),2) . ' seconds . . . zzzzzzzzzzzzzz<br>';
flush();
usleep($rand);
$c++;
}
WHAT I'VE GOT BEGINS HERE:
<br />
<br />
This page is loading.<br />
<?php
for($i=0;$i<5;$i++){
flush(); sleep(2);
?>
Almost there...<br />
<?php
}
?>
<?php flush(); sleep(2); ?>
Done.<br />
</BODY>
</HTML>
...and now the lower block of code sleeps fine, sequentially. Output is properly staggered (instead of arriving all in a lump at the end of 10 secs).
It's weird because I don't know what the above is doing that would make everything in the block below work all right. If I remove it, my block doesn't work (i.e., the output accumulates and then spills en masse at the end). If I remove only bits and pieces of the code above, then my thing wants to jump forward a little (but sequentially outputs the rest fine).
I have no idea what the preceding code is doing that makes my (latter block) work the way it should, or how to abbreviate it so that it still makes the latter block fully work, or even how to make the above code invisible on the page while still allowing the latter block to work accurately.
(I've tested the script on both Windows 7 Caucho Resin PHP 5 and Linux Apache CGI-BIN PHP 4 platforms. Identical results.)
It sounds like you should be using flush() instead of sleep().
http://us3.php.net/manual/en/function.flush.php

Categories