来解决效率与定时任务的功能,主要作用是可以将定时任务与线程池功能结合使用
1:ScheduledExecutorService executor =Executors.newSingleThreadScheduledExecutor();
newSingleThreadScheduledExecutor() 在 JDK 的源码里
实例化 new ScheduledThreadPoolExecutor(1) 对象时传入的参数为11,是单任务执行的计划任务池。
源码:
public static SchedluedExecutorService =newSingleThreadScheduledExecutor(){
return new DelegatedScheduledExecutorService(new ScheduledThreadPoolExecutor(1));
}
2:ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
newScheduledThreadPool(pooSize)
在 JDK 中的源码:
public static ScheduledExecutorService newScheduledThreadPool (int corePoolSize){
return new ScheduledThreadPoolExecutor(corePoolSzie);
}
周期性执行方法:
scheduleAtFixedRate(Runable command,long initialDelay,long period,TimeUnit.unit)
启动项目,initialDelay后开始执行程序,然后每过period时间周期性执行。
也就是第二次执行是在initialDelay+period执行。第三次执行在initialDelay+2*period执行
执行任务时间 > period 预定的周期时间,也就是产生了超时的效果,比如 执行任务用了5秒。执行效果相当于每隔 5秒 执行一次任务
scheduleWithFixedDelay(Runnable command,long initialDelay.long delay,TimeUnit.unit)
启动项目,initialDelay后开始执行程序,然后每过执行完本次程序所用的时间+period时间周期性执行。在每一次执行终止到下一次要执行的时间差事delay
执行任务时间 > period 预定的周期时间,比如执行一次任务的时间需要5秒,即5秒执行完之后,再延时delay秒,故执行效果相当于每隔执行任务时间+delay 秒执行一次任务