① 如果任务在周期内正常结束掉的话scheduleAtFixedRate和scheduleWithFixedDelay没有差别
public void start() {
ScheduledExecutorService pool = Executors
.newScheduledThreadPool(1);
System.out.println("this task startTime ");
pool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("this task id = " + (number+1));
number++;
}
}, 0,3000, TimeUnit.MILLISECONDS);
}
scheduleWithFixedDelay 如下图
② 如果任务在周期内没有正常结束掉的话scheduleAtFixedRate会努力追赶原本的计划(已经晚了我得跑快点), scheduleWithFixedDelay则会摆烂不会追赶原本的计划(反正都晚了,就这样吧,爱咋咋地)
public void start() {
ScheduledExecutorService pool = Executors
.newScheduledThreadPool(1);
System.out.println("this task startTime ");
pool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
System.out.println("this task id = " + (number+1));
if (number <= 3) {
Thread.sleep(8000);
}
number++;
} catch (Exception e) {
}
}
}, 0,3000, TimeUnit.MILLISECONDS);
}
这里我们主动设置了前3个任务都超时8s, 之后的任务恢复正常,我们看下面的日志
我们看到这个输出有点怪异,为啥在05s的时候一下子执行了那么多次任务呢?
注意看如果任务不超时, 40:33 按照预期 执行第12个任务的时间应该是 41:06 , 正好会和日志对的上,这下子就能理解了,它是在追赶原本的预期节奏,哪怕是一秒钟也会发很多请求。
我们换成scheduleWithFixedDelay再试试
才不管原来的节奏呢,慢了就慢了,我就按照慢着的节奏走。