Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 584
Yeak Avatar asked Mar 14 '13 16:03

Yeak


People also ask

Is there a wait function in PHP?

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.

How do you call a PHP function after some time?

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.

What is the sleep function called in PHP?

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 do I stop a PHP script?

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.


2 Answers

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 } 
like image 185
mavili Avatar answered Sep 28 '22 03:09

mavili


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.

  1. Your script will run slowly. Choking the server if several users are running that script.
  2. Your server may timeout for some users.
  3. HDD access is a costly resource.
  4. 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.

like image 39
Husman Avatar answered Sep 28 '22 04:09

Husman