my $timeout = 10; #10 seconds timeout foreach my $source (@sources) { my dbh = connect_to_db($source); my sth = $dbh->prepare(YOU_QUERY_GOES_HERE); eval { local $SIG{ALRM} = sub {die "alarmn";}; alarm($timeout); $sth->execute(YOUR_PARAMS); alarm(0); }; unless ($@) { last; #ALL OK } else { #didnt print "Timeout happens!n"; } }