homepage Welcome to WebmasterWorld Guest from 54.197.211.197
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / Perl Server Side CGI Scripting
Forum Library, Charter, Moderators: coopster & jatar k & phranque

Perl Server Side CGI Scripting Forum

    
Timeout on a webservice call
agentalpha

5+ Year Member



 
Msg#: 3454214 posted 7:42 pm on Sep 18, 2007 (gmt 0)

I'm currently calling a web service that returns some XML like so:


use HTTP::Request::Common;
use LWP::UserAgent;
use XML::Parser;
use CGI;
use URI::Escape;

my $ua = LWP::UserAgent->new;
my $uri = "http://myWebService.com?param1=" . $gVar1 . "&param=" . $gVar2;

my $req = HTTP::Request::Common::POST( $uri);

my $result = $ua->request( $req );
my $webServiceXML = $result->content;

Is there a way to set some sort of timeout around the call in case the web service is down? Currently if the server the web service is on is down the script just runs and runs eventually coming back with a blank screen. I want to add something like:


if(web service-Call-Time > 10 seconds) {
web service is down, insert exception code here
}

Any ideas?

 

SeanW

10+ Year Member



 
Msg#: 3454214 posted 11:14 pm on Sep 18, 2007 (gmt 0)

Look at the LWP::UserAgent manpage for the new method

my $ua = LWP::UserAgent->new( { timeout => 10} );
...
my $result = blah

It's been a while, but I think $result will be undef if it times out.

Sean

upside

10+ Year Member



 
Msg#: 3454214 posted 6:20 am on Sep 26, 2007 (gmt 0)

The timeout in LWP doesn't work if the host is unreachable. Use alarm if your OS supports it. Here is (untested) code that should implement both timeouts:

use HTTP::Request::Common;
use LWP::UserAgent;
use XML::Parser;
use CGI;
use URI::Escape;
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
my $uri = "http://myWebService.com?param1=" . $gVar1 . "&param=" . $gVar2;
my $req = HTTP::Request::Common::POST( $uri);
my $result;
eval {
local $SIG{ALRM} = sub { die "alarm\n" };
alarm(10);
$result = $ua->request($req);
alarm(0);
};
return 'web service is down' if $@ eq "alarm\n";
my $webServiceXML = $result->content;

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / Perl Server Side CGI Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved