我可以让一段代码超时吗?

发布于 2024-11-29 19:14:09 字数 323 浏览 1 评论 0原文

我正在使用一个与服务器进行远程连接的类。我遇到的一个问题是,如果连接没有得到响应,它将等待直到得到响应。

该类没有内置超时功能,并且如果可以避免的话我不想修改它

有什么方法可以将一段代码包装成这样的吗?

try(timeout seconds){
}catch(){
    //exception handle
}timeout(){
    // timeout handline
}

编辑:我使用远程连接作为一个问题。我还需要解决其他问题,例如使用 exec 进行系统调用或其他类似的事情。

I'm working with a class that makes a remote connection to a server. A problem that I'm running into is if the connection doesn't get a response, it'll wait until it does.

This class does not have a timeout built into it, and I don't want to modify it if I can avoid it.

Is there any way that I can wrap a section of code in something like this?

try(timeout seconds){
}catch(){
    //exception handle
}timeout(){
    // timeout handline
}

EDIT: I use the remote connection as one problem. I have others that I need to solve with this as well, like making system calls with exec or other similar things.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

潦草背影 2024-12-06 19:14:09

不仅仅针对代码的一部分。

不过,还有替代解决方案,无需根据要求修改原始代码:

set_time_limit

set_time_limit() 如果运行时间过多,将中止整个脚本。您仍然可以设置关闭功能

pcntl_alarm

pcntl_alarm() 将发送在给定的时间后向您发送一个信号,这可能会中止该类当时正在执行的阻塞系统调用,并且这可能允许您要求该类中止其操作(如果它提供了此类方法)。不过,这可能不适合 Web 服务器环境。

默认超时

如果类使用流函数,您可以设置默认超时:

ini_set('default_socket_timeout', 5);
stream_context_set_default(array(
    'http' => array(
        'timeout' => 5, 
    ),
));

在单独的进程中执行

您可以使用 进行分叉pcntl_fork(),但这不适合服务器环境。

您还可以使用 proc_openpopen 在单独的进程中执行 PHP 脚本,如果运行时间过长则将其终止。 (进程生成后,使用 stream_select.)

或者设置一个服务器来处理这些任务。

Not for only a section of the code.

There is however alternative solutions, without modifying the original code, as requested:

set_time_limit

set_time_limit() will abort the whole script if it runs for too many time. You could still setup a shutdown function.

pcntl_alarm

pcntl_alarm() will send you a signal after a given amount of time, which may abort the blocking syscall the class is doing at that time, and this may allow you to ask the class to abort its operations if it provides such method. This may not be suitable in a web server environment, though.

Default timeouts

If the class is using stream functions, you may be able to set a default timeout:

ini_set('default_socket_timeout', 5);
stream_context_set_default(array(
    'http' => array(
        'timeout' => 5, 
    ),
));

Execute in a separate process

You could fork with pcntl_fork(), but this is not suitable in a server environment.

You could also use proc_open or popen to execute a PHP script in a separate process and kill it if it runs for a too long time. (After the process is spawned, do an idle wait on the process' stdout stream with stream_select.)

Or setup a server for handling these tasks.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文