2

I have the following code to request a header from an 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'); 

...

I don't know the reason, but the request seems very slow, it takes more than 10 seconds for me. I just want to implement a rule: if it does not return anything in 10 seconds, it should give up and resume the commands after the print.

Does anyone know how to implement this?

SoftTimur
  • 5,630
  • 38
  • 140
  • 292
  • 3
    LWP::UserAgent has a [timeout setting](https://metacpan.org/pod/LWP::UserAgent#ua-timeout) that defaults to 3 minutes. See http://stackoverflow.com/q/10989783/176646 – ThisSuitIsBlackNot Oct 06 '15 at 19:18
  • Note this caveat: "The requests is aborted if no activity on the connection to the server is observed for *timeout* seconds. This means that the time it takes for the complete transaction and the request() method to actually return might be longer." – melpomene Oct 06 '15 at 19:21

1 Answers1

0

You could use 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
    } 
}
Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133