homepage Welcome to WebmasterWorld Guest from 54.83.133.189
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Subscribe to WebmasterWorld
Visit PubCon.com
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




msg:3454216
 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




msg:3454371
 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




msg:3461119
 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.
Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About
© Webmaster World 1996-2014 all rights reserved