【问题标题】:How to check if execution of script exceeds x seconds?如何检查脚本的执行是否超过 x 秒?
【发布时间】:2017-03-15 12:15:53
【问题描述】:

我有一个使用 API 的 PHP 脚本。有时 API 可能很快,有时很慢。有没有办法检查 get_contents(); 的执行时间?高于前。 2 秒?

如果超过这个数量,我希望包含的脚本停止,并执行原始文件。

例如:

<?php 

    include("file.php"); //if more than 2 sec, continue

    echo "Hello world";

?>

【问题讨论】:

标签: php


【解决方案1】:

您可以使用set_time_limit函数设置最大时间限制

.... //some logic
const MAX_EXECUTION_TIME = 2; // for 2 seconds
set_time_limit(self::MAX_EXECUTION_TIME);
file_get_contents(...);
.... // some other logic

【讨论】:

  • 如果执行时间大于你设置的时间,使用set_time_limit会抛出错误!
  • Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error.
  • 你是对的。也许 try catch 块会起作用?或者更好的选择可能是使用 curl。所以像curl_setopt($ch, CURLOPT_TIMEOUT, 2) 这样的东西应该可以解决问题
  • 对不起,我误解了 OP 的问题。据我所知,没有办法事先知道脚本的执行时间,因为它取决于很多可变因素,例如服务器速度,例如
  • 还有一点很重要,set_time_limit 设置了整个脚本的时间限制,而不仅仅是其中的一部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-17
  • 2011-01-24
  • 1970-01-01
  • 2016-01-26
  • 2017-08-27
  • 1970-01-01
相关资源
最近更新 更多