ScheduledExecutorService

来解决效率与定时任务的功能,主要作用是可以将定时任务与线程池功能结合使用

 

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 秒执行一次任务

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值