Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stop executing loop after a selected time

Tags:

loops

php

I wanna stop executing loop after a selected time. Means when looping it will try to execute an argument and take a long time then it will finish working and go to next argument. such as :

for ($i=2 ; $i <= 100 ; $i++)

Here, suppose it will loop 3,4,5,6,7,8,9,10 and in 11 it will take a long time to execute. So i just wanna stop it after ( i.e 10 seconds ) and take next option i mean 12,13,14... etc. So, how can i do this. I set up this set_time_limit(10); , but it is not working here.

like image 785
Imran Abdur Rahim Avatar asked Sep 17 '25 20:09

Imran Abdur Rahim


2 Answers

You can use microtime() to measure time elapsed. Note that this will only break after an iteration has completed.

$start = microtime(true);
$limit = 10;  // Seconds

for ($i=2 ; $i <= 100 ; $i++) {
  if (microtime(true) - $start >= $limit) {
    break;
  }
}
like image 139
Znarkus Avatar answered Sep 19 '25 12:09

Znarkus


That is quite complex. You will have to create a separate thread to do the processing in, so your main thread can check if it has been running for too long.

Those threads are called 'forks' in PHP.

You'll have to investigate the Process Control functions and especially [pcntl_fork][2]. Then, using pcntl_sigtimedwait, you can wait for the forked process during a given timeout. When pcntl_sigtimedwait returns, you can check its returned value to see if the process timed out.

like image 27
GolezTrol Avatar answered Sep 19 '25 11:09

GolezTrol