foreach ($arr as $k => $v)
{
$r = my_func($v);
$new[$k] = $r;
}如果my_func()的执行时间超过10秒,那么$r将返回false,否则(如果执行时间少于10秒),它将返回true;
附加信息:my_func()实际上会读取一个URL,有时会花很长时间。如果花费的时间超过10秒,我希望返回false。
发布于 2012-03-22 14:25:41
在PHP中,您不能通过函数来限制执行时间。但是,不要绝望:如果您提到的函数读取URL,您可以使用curl扩展,它具有通过curl_setopt设置选项的选项,如下所示:
CURLOPT_TIMEOUT允许执行cURL函数的最大秒数。CURLOPT_CONNECTTIMEOUT尝试连接时等待的秒数。
使用它们,您可以限制使用curl进行URL处理所花费的实际时间。
你也可以使用http扩展,它也允许你做http连接并且有timeout options。
最后,您可以使用context options to file_get_contents
$opts = array('http' =>
array(
'timeout' => 1.5 // 1.5 seconds
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/getdata.php', false, $context);发布于 2012-03-22 14:26:35
如果my_func读取一个URL,而你不希望它花费超过给定的超时时间,如果你使用了正确的URL函数,你应该能够指定超时时间,如果超过这个时间,调用就会失败。
如果您使用的是cURL,您可以使用curl_multi_exec手动获取此行为,或者仅指定超时,然后函数将返回false。
示例:
function my_func($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // timeout after 10 seconds
// .. set other options as needed
$result = curl_exec($ch);
if ($result === false) {
// timeout or other failure
return false;
}
}现在,由于超时,函数的运行时间不会超过大约10秒。您还可以使用curl_errno()检查超时:
if (curl_errno($ch) == 28) {
// timeout was exceeded
}发布于 2012-03-22 14:09:29
做一些类似的事情:
foreach ($arr as $k => $v)
{
$before = time()
$r = my_func($v);
$after = time();
$timeDelta = $after - $before;
if($timeDelta < 10){
$r = true;
}
$new[$k] = $r;
}https://stackoverflow.com/questions/9817215
复制相似问题