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?
Description ¶ The wait function suspends execution of the current process until a child has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function.
Using pcntl_alarm... Alternatively, if you have the Process Control support enabled in your build of PHP, you might be able to use pcntl_alarm to call a signal handler after a certain amount of time has elapsed.
The sleep() function delays execution of the current script for a specified number of seconds. Note: This function throws an error if the specified number of seconds is negative.
How we can use the PHP's exit function to stop the execution of remaining code. exit is usually used right after sending final output to a browser, or to stop a script in case there was an error. When exit is used it will stop code-execution completely and exit PHP.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With