2

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.

Imran Abdur Rahim
  • 397
  • 1
  • 6
  • 19

2 Answers2

2

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;
  }
}
Znarkus
  • 22,406
  • 22
  • 77
  • 108
  • it will check at start of iteration but probably he want a solution to break the loop during the iteration. – Mansoor Jafar Nov 02 '12 at 12:54
  • may be it will break my whole script if i put it globally ? @mansoor , ya right . – Imran Abdur Rahim Nov 02 '12 at 13:01
  • @mansoor That's what I meant with "Note that this will only break after an iteration has completed". Can't come up with a scenario where this is *not* what you want – Znarkus Nov 02 '12 at 17:15
0

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.

GolezTrol
  • 111,943
  • 16
  • 178
  • 202