我可以让一段代码超时吗?
我正在使用一个与服务器进行远程连接的类。我遇到的一个问题是,如果连接没有得到响应,它将等待直到得到响应。
该类没有内置超时功能,并且如果可以避免的话我不想修改它。
有什么方法可以将一段代码包装成这样的吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不仅仅针对代码的一部分。
不过,还有替代解决方案,无需根据要求修改原始代码:
set_time_limit
set_time_limit()
如果运行时间过多,将中止整个脚本。您仍然可以设置关闭功能。pcntl_alarm
pcntl_alarm()
将发送在给定的时间后向您发送一个信号,这可能会中止该类当时正在执行的阻塞系统调用,并且这可能允许您要求该类中止其操作(如果它提供了此类方法)。不过,这可能不适合 Web 服务器环境。默认超时
如果类使用流函数,您可以设置默认超时:
在单独的进程中执行
您可以使用 进行分叉
pcntl_fork()
,但这不适合服务器环境。您还可以使用
proc_open
或popen
在单独的进程中执行 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:
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
orpopen
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 withstream_select
.)Or setup a server for handling these tasks.