超时 PHP 中的函数 [英] Timeout a function in PHP
问题描述
有没有办法让函数超时?我有 10 分钟的时间来完成一项工作.该作业包括一个 for 循环,这是一个示例:
Is there a way to timeout a function? I have 10 minutes to perform a job. The job includes a for loop, here is an example:
<?php
foreach($arr as $key => $value){
some_function($key, $value); //This function does SSH and SFTP stuff
}
?>
$arr 有 15 个元素,而 some_function() 有时可能需要 1 分钟以上.事实上,一旦它被绞死了 5 分钟.
$arr has 15 elements and some_function() sometimes may take more than 1 minutes. In fact once it got hanged for 5 minutes.
有没有办法让函数调用超时并继续处理 $arr 中的下一个元素?
Is there a way I can timeout the function call and move on with next element in $arr?
谢谢!!
推荐答案
这取决于您的实施.PHP 中 99% 的函数都是阻塞的.意思是在当前功能完成之前不会继续处理.但是,如果函数包含循环,您可以添加自己的代码以在满足特定条件后中断循环.
It depends on your implementation. 99% of the functions in PHP are blocking. Meaning processing will not continue until the current function has completed. However, if the function contains a loop you can add in your own code to interrupt the loop after a certain condition has been met.
像这样:
foreach ($array as $value) {
perform_task($value);
}
function perform_task($value) {
$start_time = time();
while(true) {
if ((time() - $start_time) > 300) {
return false; // timeout, function took longer than 300 seconds
}
// Other processing
}
}
无法中断处理的另一个示例:
Another example where interrupting the processing IS NOT possible:
foreach ($array as $value) {
perform_task($value);
}
function perform_task($value) {
// preg_replace is a blocking function
// There's no way to break out of it after a certain amount of time.
return preg_replace('/pattern/', 'replace', $value);
}
这篇关于超时 PHP 中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!