Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retry Task Framework

Tags:

java

I have a number of situations where I need to retry a task n-times if it fails (sometimes with some form of back-off-before-retry logic). Generally, if an exception is thrown, the task should be retried up to the max-retry count.

I can easily write something to do this fairly generically, but not wanting to re-invent the wheel I was wondering if anyone can recommend any frameworks for this. The only thing I have been able to find is: Ant Retry but I don't want to use Ant tasks directly in my application.

Thanks

like image 341
Scruffers Avatar asked Jan 19 '11 17:01

Scruffers


People also ask

What is retry strategy?

This strategy specifies the number of times it should retry, the delay between each attempt, and the actions to take after a failed attempt.

What is the name of the Microsoft retry framework?

Microsoft Entity Framework provides facilities for retrying database operations.

How do I enable retry in spring boot?

First, you need to enable Spring Retry. You can achieve this by adding the @EnableRetry annotation to your @SpringBootApplication or @Configuration class. You can now use @Retryable to annotate any method to be a candidate or retry and @Recover to specify fallback methods.

What is @retryable in spring boot?

Spring Retry provides the ability to automatically re-invoke a failed operation. This is helpful when errors may be transient in nature. For example, a momentary network glitch, network outage, server down, or deadlock. You can configure the. spring-retry.


2 Answers

Check out Failsafe. It's a simple, zero-dependency library for performing retries, and supports synchronous and asynchronous retries, Java 8 integration, event listeners, integration with other async APIs, etc:

RetryPolicy retryPolicy = new RetryPolicy()   .handle(ConnectException.class, SocketException.class);   .withMaxRetries(3);  Connection connection = Failsafe.with(retryPolicy).get(() -> connect()); 

Doesn't get much easier.

like image 133
Jonathan Avatar answered Oct 04 '22 14:10

Jonathan


You can use RetriableTasks as outlined in this post: Retrying Operations in Java. You can quite easily change its waiting algorithm if you like.

Sample code:

//creates a task which will retry 3 times with an interval of 5 seconds RetriableTask r = new RetriableTask(3, 5000, new Callable(){     public Object call() throws Exception{         //put your code here     } }); r.call(); 
like image 21
dogbane Avatar answered Oct 04 '22 14:10

dogbane