Set timeout for specific function

4

I have a multi-function script .

I want to set a specific timeout (type set_time_limit ) for a function , and if it pops up, it "disregards" and continue running the loop / script.

Example:

function teste(){
    sleep(10);
}

foreach($array as $v) {
    echo $v;
    teste();
}

Considering the example, the teste() function will run for 10 seconds on each loop.

Then I want to set a timeout of 3 seconds for the function, and if I "pop" the time, it discards, and continues the loop .

  • Is there a possibility?
asked by anonymous 18.09.2018 / 20:28

1 answer

0

My curiosity led me to this answer. I do not know if it is the best solution, but it works. To do what you want I got it using exec of php to run the file containing the teste() function in the background. So:

$array = [1,2,3,4,5,2,1];

foreach($array as $v) {
    $var = exec('C:\xampp\php\php.exe  '. __DIR__ .'\teste.php '.$v, $saida);
    echo $var;
}

test.php file

error_reporting (0);
set_time_limit(3); 
function teste($sec){
    sleep($sec);
    echo "executou > $sec - ";
}
$sec = $argv[1];
teste($sec);

The $v variable is posted as an argument to the script that is retrieved in $sec .

Result

executou > 1 -executou > 2 -executou > 3 -executou > 2 -executou > 1 -
    
19.09.2018 / 03:06