版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aitangyong/article/details/53894899
AttemptTimeLimiter和guava的TimeLimiter基本是一样的,是为了限制某个任务的执行时间。比如我希望一个Callable任务执行时间不超过5s,如果超过抛异常TimeoutException。
import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.TimeLimiter;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
public class TestTimeLimiter {
public static void main(String[] args) throws Exception {
TimeLimiter timeLimiter = new SimpleTimeLimiter();
timeLimiter.callWithTimeout(buildTask(), 5, TimeUnit.SECONDS, false);
}
private static Callable<Boolean> buildTask() {
return new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
long start = System.currentTimeMillis();
long end = start;
while (end - start <= 10 * 1000) {
end = System.currentTimeMillis();
}
return true;
}
};
}
}
AttemptTimeLimiter功能与之类似,保证某次重试的执行时间不超过特定值。
public class TestLimit {
private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
public static void main(String[] args) throws Exception {
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfException()
.retryIfResult(Predicates.equalTo(false))
.withAttemptTimeLimiter(AttemptTimeLimiters.fixedTimeLimit(1, TimeUnit.SECONDS))
.withStopStrategy(StopStrategies.stopAfterAttempt(5))
.build();
System.out.println("begin..." + df.format(new Date()));
try {
retryer.call(buildTask());
} catch (Exception e) {
System.err.println("still failed after retry." + e.getCause().toString());
}
System.out.println("end..." + df.format(new Date()));
}
private static Callable<Boolean> buildTask() {
return new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
System.out.println("called");
long start = System.currentTimeMillis();
long end = start;
while (end - start <= 10 * 1000) {
end = System.currentTimeMillis();
}
return true;
}
};
}
}