ScheduleExecutorService

ScheduleExecutorService

1.按指定频率周期执行某个任务。

初始化延迟0ms开始执行,每隔100ms重新执行一次任务。

[java]  view plain  copy
  1. /** 
  2.  * 以固定周期频率执行任务 
  3.  */  
  4. public static void executeFixedRate() {  
  5.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
  6.     executor.scheduleAtFixedRate(  
  7.             new EchoServer(),  
  8.             0,  
  9.             100,  
  10.             TimeUnit.MILLISECONDS);  
  11. }  
间隔指的是连续两次任务开始执行的间隔。

2.

按指定频率间隔执行某个任务。

初始化时延时0ms开始执行,本次执行结束后延迟100ms开始下次执行。

[java]  view plain  copy
  1. /** 
  2.  * 以固定延迟时间进行执行 
  3.  * 本次任务执行完成后,需要延迟设定的延迟时间,才会执行新的任务 
  4.  */  
  5. public static void executeFixedDelay() {  
  6.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
  7.     executor.scheduleWithFixedDelay(  
  8.             new EchoServer(),  
  9.             0,  
  10.             100,  
  11.             TimeUnit.MILLISECONDS);  
  12. }  
举例:

周期定时执行某个任务。

有时候我们希望一个任务被安排在凌晨3点(访问较少时)周期性的执行一个比较耗费资源的任务,可以使用下面方法设定每天在固定时间执行一次任务。

/**
 * 每天晚上8点执行一次
 * 每天定时安排任务进行执行
 */
public static void executeEightAtNightPerDay() {
	ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
	long oneDay = 24 * 60 * 60 * 1000;
	long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();
	initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;

	executor.scheduleAtFixedRate(
			new EchoServer(),
			initDelay,
			oneDay,
			TimeUnit.MILLISECONDS);
}
<p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial;"><span style="font-weight: bold;">一些问题</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial;">上面写的内容有不严谨的地方,比如对于scheduleAtFixedRate方法,当我们要执行的任务大于我们指定的执行间隔时会怎么样呢?</p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial;">对于中文API中的注释,我们可能会被忽悠,认为无论怎么样,它都会按照我们指定的间隔进行执行,其实当执行任务的时间大于我们指定的间隔时间时,它并不会在指定间隔时开辟一个新的线程并发执行这个任务。而是等待该线程执行完毕。</p><div>
</div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值