【问题标题】:Skip if a request takes too much time如果请求花费太多时间则跳过
【发布时间】:2023-03-10 04:21:01
【问题描述】:

我有以下代码从 URL 请求标头:

#!/usr/bin/env perl
use strict;
use warnings;

use LWP;
use Data::Dumper;

my $request = HTTP::Request -> new ( HEAD => 'http://www.vliruos.be/media/6352100/nss2015_annex_3_budget.xlsx' ); 
my $agent = LWP::UserAgent -> new;
my $response = $agent -> request ( $request );
print $response -> header ( 'Content-Length'); 

...

我不知道原因,但是请求似乎很慢,对我来说需要10多秒。我只是想实现一个规则:如果它在 10 秒内没有返回任何内容,它应该放弃并恢复 print 之后的命令。

有人知道如何实现吗?

【问题讨论】:

  • LWP::UserAgent 有一个timeout setting,默认为 3 分钟。见stackoverflow.com/q/10989783/176646
  • 请注意此警告:“如果在 timeout 秒内未观察到与服务器的连接上的任何活动,则请求将中止。这意味着完成事务所需的时间并且实际返回的 request() 方法可能会更长。”

标签: perl time timer exception-handling


【解决方案1】:

你可以使用SIGALRM

$SIG{ALRM} = sub { die "timeout" };

eval {
    alarm(10);
    # long-time operations here
    alarm(0);
};

if ($@) {
    if ($@ =~ /timeout/) {
                            # timed out; do what you will here
    } else {
        alarm(0);           # clear the still-pending alarm
        die;                # propagate unexpected exception
    } 
}

【讨论】:

  • 为什么要双重评估?为什么最后还有一个alarm 0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-01
  • 2015-06-05
  • 2014-03-22
  • 2014-01-05
  • 1970-01-01
  • 2022-12-18
  • 2016-12-28
相关资源
最近更新 更多