我正在使用LWP从网页下载内容,我想限制它等待页面的时间。
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
$ua->env_proxy;
$response = $ua->get("http://XML File");
$content = $response->decoded_content;问题是服务器偶尔会死锁(我们正在尝试找出原因),并且请求永远不会成功。因为服务器认为它是活动的,所以它保持套接字连接打开,因此LWP::UserAgent的超时值对我们没有任何好处。对请求强制绝对超时的最佳方法是什么?
每当超时达到它的极限时,它就会死掉,我不能继续执行脚本了!整个脚本都在一个循环中,它必须按顺序获取XML文件。我真的很想正确地处理这个超时,让脚本继续到下一个地址。有人知道怎么做吗?谢谢!!
发布于 2013-04-09 19:08:30
我以前在https://stackoverflow.com/a/10318268/1331451中遇到过类似的问题。
您需要做的是添加一个$SIG{ALRM}处理程序并使用alarm调用它。您可以在调用之前设置alarm,然后直接取消它。然后,您可以查看返回的HTTP::结果。
警报将触发信号,Perl将调用信号处理程序。在它中,你可以直接使用die或者只使用die。eval是为了让die no破坏整个程序。如果信号处理程序被调用,alarm将自动复位。
您还可以向处理程序添加不同的die消息,并在以后使用$@进行区分,就像@larsen在他的回答中所说的那样。
下面是一个例子:
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new;
my $res;
eval {
# custom timeout (strace shows EAGAIN)
# see https://stackoverflow.com/a/10318268/1331451
local $SIG{ALRM} = sub {
# This is where it dies
die "Timeout occured...";
}; # NB: \n required
alarm 10;
$res = $ua->request($req);
alarm 0;
};
if ($res && $res->is_success) {
# the result was a success
}信号的
发布于 2013-04-09 19:09:19
通常,如果您希望捕获和控制可能死掉的代码段,则可以使用eval块。
while( … ) { # this is your main loop
eval {
# here the code that can die
};
if ($@) {
# if something goes wrong, the special variable $@
# contains the error message (as a string or as a blessed reference,
# it depends on how the invoked code threats the exception.
}
}您可以在the eval function的文档中找到更多信息
https://stackoverflow.com/questions/15899855
复制相似问题