在PHP中超时一个函数 [英] Timeout a function in PHP

查看:179
本文介绍了在PHP中超时一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法超时的功能?我有十分钟的时间去完成一项工作。

 <?php 
foreach($ arr as $ key => $ value){
some_function($ key,$ value); //这个函数使用SSH和SFTP的东西
}
?>

$ arr有15个元素,some_function()有时可能需要1分钟以上。事实上,一旦它被绞死了5分钟。

有没有办法让超时的函数调用和下一个元素在$ arr?



谢谢!!

解决方案

这取决于您的实施。 PHP中的99%的功能是阻塞的。在当前功能完成之前,意义处理将不会继续。然而,如果函数包含一个循环,你可以添加自己的代码,以满足某些条件后中断循环。



类似这样:


$ b $

  foreach($ array as $ value){
perform_task($ value);


函数perform_task($ value){
$ start_time = time(); ((time() - $ start_time)> 300){
return false; $($)
$ b while(true){
if //超时,函数耗时超过300秒
}
//其他处理


code pre >

另一个中断处理的例子是不可能的:

$ $ $ $ $ $ foreach $ array作为$ value){
perform_task($ value);


函数perform_task($ value){
// preg_replace是一个阻塞函数
//在一定数量的时间。
返回preg_replace('/ pattern /','replace',$ value);
}


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 has 15 elements and some_function() sometimes may take more than 1 minutes. In fact once it got hanged for 5 minutes.

Is there a way I can timeout the function call and move on with next element in $arr?

Thank you!!

解决方案

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.

Something like this:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆