My Perl application uses resources that become temporarily unavailable at times, causing exceptions using die
. Most notably, it accesses SQLite databases that are shared by multiple threads and with other applications using through DBIx::Class
. Whenever such an exception occurs, the operation should be retried until a timeout has been reached.
I prefer concise code, therefore I quickly got fed up with repeatedly typing 7 extra lines for each such operation:
use Time::HiRes 'sleep';
use Carp;
# [...]
for (0..150) {
sleep 0.1 if $_;
eval {
# database access
};
next if $@ =~ /database is locked/;
}
croak $@ if $@;
... so I put them into a (DB access-specific) function:
sub _retry {
my ( $timeout, $func ) = @_;
for (0..$timeout*10) {
sleep 0.1 if $_;
eval { $func->(); };
next if $@ =~ /database is locked/;
}
croak $@ if $@;
}
which I call like this:
my @thingies;
_retry 15, sub {
$schema->txn_do(
sub {
@thingies = $thingie_rs->search(
{ state => 0, job_id => $job->job_id },
{ rows => $self->{batchsize} } );
if (@thingies) {
for my $thingie (@thingies) {
$thingie->update( { state => 1 } );
}
}
} );
};
Is there a better way to implement this? Am I re-inventing the wheel? Is there code on CPAN that I should use?