Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Can't time out a $sth-fetchrow()

by Skeeve (Vicar)
on May 27, 2011 at 07:32 UTC ( #906940=perlquestion: print w/replies, xml ) Need Help??
Skeeve has asked for the wisdom of the Perl Monks concerning the following question:

I have a query which currently requires too much time. So I'd like to set a timeout and tried it like this:

my $message= "This message should not appear"; my $exitcode= $UNKNOWN; eval { my $dbh = undef; my $sth = undef; local $SIG{ALRM} = sub { if ($sth) { $sth->cancel(); } die $timeoutstr; }; alarm $timeout; $dbh = DBI->connect("dbi:Oracle:$sid", $user, $pass, { AutoCommit => 0, RaiseError => 0, PrintErro +r => 1 } ); $sth = $dbh->prepare($stm) or do_exit($UNKNOWN, $dbh->errstr); $sth->execute() or do_exit($UNKNOWN, $dbh->errstr); if(my @row = $sth->fetchrow()) { # ... } else { $exitcode= $UNKNOWN; $message= "Did not get a result: " . ($DBI::errstr || ''); } $sth->finish(); $dbh->disconnect(); alarm 0; }; if ($@ and $@ eq $timeoutstr) { do_exit($CRITICAL, "Timeout after $timeout sec\n"); }

Unfortunately the alarm handler seems to be not invoked at all until I press Ctrl-C.

Do I make a mistake here? Are there workarounds?


Replies are listed 'Best First'.
Re: Can't time out a $sth-fetchrow()
by mje (Curate) on May 27, 2011 at 07:54 UTC

    Your die string will not be $timeoutstr so you need to use =~ on line 29.


    You might want to take a look at Signal Handling and Canceling Operations.

    I use signals with DBD::Oracle but I use Sys::SigAction.

    An alternative (although I'm not sure it is available for DBD::Oracle) is asynchronous operations which some DBDs support.

      Why do you think, my die string will not be $timeoutstr? I'm just curious because now, where I use what you also suggested, Sys::SigAction, it works. The "eq" also works.


        Because it contains something like "timeout at line 16." because Perl added the line number.

Re: Can't time out a $sth-fetchrow()
by Skeeve (Vicar) on May 27, 2011 at 07:51 UTC

    I found a solution! Thanks for your time ;)


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://906940]
Approved by philipbailey
and the voices are still...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2018-06-24 08:59 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.