Action-Retry
view release on metacpan or search on metacpan
lib/Action/Retry.pm view on Meta::CPAN
=head1 VERSION
version 0.24
=head1 SYNOPSIS
# Simple usage, will attempt to run the code, retrying if it dies, retrying
# 10 times max, sleeping 1 second between retries
# functional interface
use Action::Retry qw(retry);
retry { do_stuff };
# OO interface
use Action::Retry;
Action::Retry->new( attempt_code => sub { do_stuff; } )->run();
# Same, but sleep time is doubling each time, and arguments passed to the
# attempted code
# OO interface
my $action = Action::Retry->new(
attempt_code => sub { my ($num, $str) = @_; ... },
strategy => 'Linear',
);
my $result = $action->run(42, "foo");
# functional interface
retry { my ($num, $str) = @_;... } strategy => 'Linear';
# Same, but sleep time is following the Fibonacci sequence
# OO interface
my $action = Action::Retry->new(
attempt_code => sub { ... },
strategy => 'Fibonacci',
);
$action->run();
# functional interface
retry { ... } strategy => 'Fibonacci';
# The code to check if the attempt succeeded can be customized. Strategies
# can take arguments. Code on failure can be specified.
# OO way
my $action = Action::Retry->new(
attempt_code => sub { ... },
retry_if_code => sub { $_[0] =~ /Connection lost/ || $_[1]->{attempt_result} > 20 },
strategy => { Fibonacci => { multiplicator => 2000,
initial_term_index => 3,
max_retries_number => 5,
}
},
on_failure_code => sub { say "Given up retrying" },
);
$action->run();
# functional way
retry { ...}
retry_if_code => sub { ... },
strategy => { Fibonacci => { multiplicator => 2000,
initial_term_index => 3,
max_retries_number => 5,
}
},
on_failure_code => sub { ... };
# Retry code in non-blocking way
# OO way
my $action = Action::Retry->new(
attempt_code => sub { ...},
non_blocking => 1,
);
while (1) {
# if the action failed, it doesn't sleep
# next time it's called, it won't do anything until it's time to retry
$action->run();
# do something else while time goes on
}
=head1 ATTRIBUTES
=head2 attempt_code
ro, CodeRef, required
The code to run to attempt doing the action. Will be evaluated taking care of
the caller's context. It will receive parameters that were passed to C<run()>
=head2 retry_if_code
ro, CodeRef
The code to run to check if we need to retry the action. It defaults to:
# Returns true if there were an exception evaluating to something true
sub { $_[0] }
It will be given these arguments:
=over
=item *
as first argument, a scalar which is the value of any exception that were
raised by the C<attempt_code>. Otherwise, undef.
=item *
as second argument, a HashRef, which contains these keys:
( run in 0.546 second using v1.01-cache-2.11-cpan-a1f116cd669 )