Reputation: 417
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.
Upvotes: 4
Views: 5082
Reputation: 24254
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;
}
}
Upvotes: 4
Reputation: 116110
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.
Upvotes: 1