Merge pull request #3943 from toint-admin/v6-dev

RetryableTask: 避免最后一次任务执行时的线程睡眠
This commit is contained in:
Golden Looly 2025-06-20 18:00:04 +08:00 committed by GitHub
commit 667915d05c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 16 additions and 14 deletions

View File

@ -37,7 +37,7 @@ public class RetryUtil {
* 没有返回值重试执行方法
*
* @param run 执行方法
* @param maxAttempts 最大的重试次数
* @param maxAttempts 最大的重试次数, 小于1不会重试, 但任务至少会被执行1次
* @param delay 重试间隔
* @param recover 达到最大重试次数后执行的备用方法
* @param exs 指定的异常类型需要重试
@ -63,7 +63,7 @@ public class RetryUtil {
* 有返回值重试执行方法
*
* @param sup 执行方法
* @param maxAttempts 最大的重试次数
* @param maxAttempts 最大的重试次数, 小于1不会重试, 但任务至少会被执行1次
* @param delay 重试间隔
* @param recover 达到最大重试次数后执行的备用方法
* @param exs 指定的异常类型需要重试
@ -88,10 +88,10 @@ public class RetryUtil {
* 没有返回值重试执行方法
*
* @param run 执行方法
* @param maxAttempts 最大的重试次数
* @param maxAttempts 最大的重试次数, 小于1不会重试, 但任务至少会被执行1次
* @param delay 重试间隔
* @param recover 达到最大重试次数后执行的备用方法
* @param predicate 自定义重试条件
* @param predicate 自定义重试条件, 返回true时表示重试
*/
public static void ofPredicate(final Runnable run, final long maxAttempts, final Duration delay,
final Supplier<Void> recover, final BiPredicate<Void, Throwable> predicate) {
@ -105,14 +105,14 @@ public class RetryUtil {
/**
* 根据异常信息进行重试
* 根据自定义结果进行重试
* 有返回值重试执行方法
*
* @param sup 执行方法
* @param maxAttempts 最大的重试次数
* @param maxAttempts 最大的重试次数, 小于1不会重试, 但任务至少会被执行1次
* @param delay 重试间隔
* @param recover 达到最大重试次数后执行的备用方法
* @param predicate 自定义重试条件
* @param predicate 自定义重试条件, 返回true时表示重试
* @param <T> 结果类型
* @return 执行结果
*/

View File

@ -109,11 +109,11 @@ public class RetryableTask<T> {
*/
private T result;
/**
* 执行方法
* 执行方法
*/
private final Supplier<T> sup;
/**
* 重试策略
* 重试策略, 返回true时表示重试
*/
private final BiPredicate<T, Throwable> predicate;
/**
@ -150,8 +150,6 @@ public class RetryableTask<T> {
* @return 当前对象
*/
public RetryableTask<T> maxAttempts(final long maxAttempts) {
Assert.isTrue(this.maxAttempts > 0, "maxAttempts must be greater than 0");
this.maxAttempts = maxAttempts;
return this;
}
@ -223,7 +221,8 @@ public class RetryableTask<T> {
private RetryableTask<T> doExecute() {
Throwable th = null;
while (--this.maxAttempts >= 0) {
// 任务至少被执行一次
do {
try {
this.result = this.sup.get();
} catch (final Throwable t) {
@ -236,8 +235,11 @@ public class RetryableTask<T> {
break;
}
// 避免最后一次任务执行时的线程睡眠
if (this.maxAttempts > 0) {
ThreadUtil.sleep(delay.toMillis());
}
} while (--this.maxAttempts >= 0);
this.throwable = th;
return this;