geekondemand has asked for the wisdom of the Perl Monks concerning the following question:

I would like to write a subroutine that will take no more than a specified amount of time to run. In this particular case I'm connecting to a web service that is sometimes not there, sometimes takes a long time, and sometimes works just fine. I then use the results to build a little snippet of HTML for use on a CGI generated page. However, if the call to the web service takes too long, I just want to return.

Ideally, I'd like some sort of wrapper sub that takes a subref and a timeout value as parameters and then returns undef on timeout and the subroutine value should the sub return in time. I could also envision some sort of closure type setup where this works.

Please enlighten this humble monk.

  • Comment on Possible to write a sub that times out???

Replies are listed 'Best First'.
Re: Possible to write a sub that times out???
by McDarren (Abbot) on Dec 25, 2005 at 09:10 UTC
    What you want here is eval.

    An example usage might be:

    my $timeout = 20; eval { local $SIG{ALRM} = sub { die "timedout" }; alarm $timeout; #Call your subroutine here.... alarm 0; }; if ($@) { # $@ will contain error message, if any }

    Hope this helps,
    Darren :)

Re: Possible to write a sub that times out???
by tirwhan (Abbot) on Dec 25, 2005 at 09:44 UTC

    If you're using LWP to connect to your web service you can use the LWP::UserAgent->timeout() method to set the timeout time (see perldoc LWP::UserAgent for more details).

    This won't work very well if the web service returns parts of the page at a time though, because the request will only time out if no activity at all takes place on the connection for the specified period. So if you've specified a timeout of 60 seconds and the service keeps returning bits with 30 or 40 seconds pause in between the request will not time out and can go on for significantly longer than a minute.


    A computer is a state machine. Threads are for people who cant program state machines. -- Alan Cox
Re: Possible to write a sub that times out???
by johnnywang (Priest) on Dec 25, 2005 at 20:53 UTC
    do "perldoc -f alarm" for some discussions.