我正在尝试用java编写一个重试机制,它在失败的情况下在3分钟后重新绑定一个函数,并最多重试3次。我不想使用Thread.Sleep,而是考虑使用ScheduledExecutorService。我正在尝试弄清楚什么是它的好实现。看起来executor.schedule()并没有在runnable中使用runnable。
我是这样想的:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
final int count = 1;
final int MAX_RETRY = 3;
Runnable runnable = () -> {
try {
//This function can fail and throw FunctionException
callMyFunction();
}
catch (FunctionException e) {
if (++count <= MAX_RETRY) {
executor.schedule(runnable, 30*60*1000);
}
}
};
executor.execute(runnable);发布于 2021-02-26 09:20:35
这段代码似乎可以工作,并且解决了我遇到的问题。我不能使用lambda来实现我的Runnable函数,因为在lambda中,没有办法让" this“引用由下面这行中的lambda表达式创建的实例:
scheduler.schedule(this, 1, TimeUnit.SECONDS);你知道怎么解决这个问题吗?
下面是完整的代码:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
AtomicInteger counter = new AtomicInteger(1);
final int MAX_RETRY = 3;
scheduler.execute(new Runnable() {
@Override
public void run () {
try {
System.out.println("Attempt number: " + counter.get());
functionCall();
scheduler.shutdown();
}
catch (Exception e) {
if (counter.get() < MAX_RETRY) {
System.out.println("Attempt number: " + counter.getAndIncrement() + " failed.");
scheduler.schedule(this, 1, TimeUnit.SECONDS);
}
else {
System.out.println("Error message: " + e.getMessage());
scheduler.shutdown();
}
}
}
});
}
public static void functionCall() {
throw new RuntimeException("Does not work");
}感谢@Turing85的帮助和有用的评论。
发布于 2021-02-26 04:08:47
我建议您使用spring-retry库,而不是编写自己的实现。
创建RetryTemplate实例。示例代码在这里- https://github.com/innovationchef/batchpay/blob/master/src/main/java/com/innovationchef/service/PayApiRetryTemplate.java
然后像这样调用你的方法-
retryTemplate.execute(arg -> callMyFunction());https://stackoverflow.com/questions/66375704
复制相似问题