最好是一个定时任务就一个线程,否则多个定时任务用一个线程,会导致延迟的情况
线程数用一个线程
ScheduledExecutorService service = ExecutorBuilder.newScheduledThreadPool(1, "test");
任务睡5秒
class MyTask implements Runnable{
int no ;
public MyTask(int no) {
this.no = no;
}
@Override
public void run() {
try {
Thread.sleep(5000);
Test1.LOG.info("I'm no-" + no);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
提交两个定时任务,每个定时任务间隔1秒
for(int i=0;i<2;i++) {
service.scheduleAtFixedRate(new MyTask(i),0, 1000, TimeUnit.MILLISECONDS);
}
结果
14:40:50.100 [test-task-0] INFO executor.Test1 - I'm no-1
14:40:55.100 [test-task-0] INFO executor.Test1 - I'm no-0
14:41:00.100 [test-task-0] INFO executor.Test1 - I'm no-1
14:41:05.101 [test-task-0] INFO executor.Test1 - I'm no-0
打印出来的情况:
由于设置1秒执行一次,但是执行任务要睡5s,所以只能5s执行一次,由于0和1两个任务轮流使用这一个线程,所以导致每个任务10s执行一次,
这种情况可以把线程池设置2,那么每个任务都会5s执行一次了
15:01:58.567 [test-task-1] INFO executor.Test1 - I'm no-1
15:01:58.567 [test-task-0] INFO executor.Test1 - I'm no-0
15:02:03.570 [test-task-0] INFO executor.Test1 - I'm no-0
15:02:03.570 [test-task-1] INFO executor.Test1 - I'm no-1