【摘抄】关于Java schedule job Timer的schedule方法详解

Timer timer = new Timer(true);
timer.schedule(TimerTask, delay, interval);

创建timer时使用new Timer(true)可以使timer线程成为一个daemon线程,这样当程序只有daemon线程的时候,它就会自动终止运行。  

Timer的schedule函数有四种:

schedule(TimerTask task, long delay, long period)  
schedule(TimerTask task, Date time, long period)  
scheduleAtFixedRate(TimerTask task, long delay, long period)  
scheduleAtFixedRate(TimerTask task, Date firstTime, long period)  

(1) 2个参数的schedule在制定任务计划时, 如果指定的计划执行时间scheduledExecutionTime<= systemCurrentTime,则task会被立即执行。scheduledExecutionTime不会因为某一个task的过度执行而改变。 
(2) 3个参数的schedule在制定反复执行一个task的计划时,每一次执行这个task的计划执行时间随着前一次的实际执行时间而变,也就是 scheduledExecutionTime(第n+1次)=realExecutionTime(第n次)+periodTime。也就是说如果第n 次执行task时,由于某种原因这次执行时间过长,执行完后的systemCurrentTime>= scheduledExecutionTime(第n+1次),则此时不做时隔等待,立即执行第n+1次task,而接下来的第n+2次task的 scheduledExecutionTime(第n+2次)就随着变成了realExecutionTime(第n+1次)+periodTime。说 白了,这个方法更注重保持间隔时间的稳定。 
(3)3个参数的scheduleAtFixedRate在制定反复执行一个task的计划时,每一次 执行这个task的计划执行时间在最初就被定下来了,也就是scheduledExecutionTime(第n次)=firstExecuteTime +n*periodTime;如果第n次执行task时,由于某种原因这次执行时间过长,执行完后的systemCurrentTime>= scheduledExecutionTime(第n+1次),则此时不做period间隔等待,立即执行第n+1次task,而接下来的第n+2次的 task的scheduledExecutionTime(第n+2次)依然还是firstExecuteTime+(n+2)*periodTime这 在第一次执行task就定下来了。说白了,这个方法更注重保持执行频率的稳定。 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值