转自http://wangzjie.iteye.com/blog/621051
schedule和scheduleAtFixedRate的区别在于,如果指定开始执行的时间在当前系统运行时间之前,scheduleAtFixedRate会把已经过去的时间也作为周期执行,而schedule不会把过去的时间算上。
比如
SimpleDateFormat fTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date d1 = fTime.parse("2005/12/30 14:10:00");
t.scheduleAtFixedRate(new TimerTask(){
public void run()
{
System.out.println("this is task you do6");
}
},d1,3*60*1000);
间隔时间是3分钟,指定开始时间是2005/12/30 14:10:00,如果我在14:17:00分执行这个程序,那么会立刻打印3次
this is task you do6 //14:10
this is task you do6 //14:13
this is task you do6 //14:16
并且注意,下一次执行是在14:19 而不是 14:20。就是说是从指定的开始时间开始计时,而不是从执行时间开始计时。
但是上面如果用schedule方法,间隔时间是3分钟,指定开始时间是2005/12/30 14:10:00,那么在14:17:00分执行这个程序,则立即执行程序一次。并且下一次的执行时间是 14:20,而不是从14:10开始算的周期(14:19)。
需要注意的是scheduleAtFixedRate和schedule在参数完全相同的情况下,执行效果是不同的。上面例子中任务只是打印一个字符串,比较简单。但如果任务比较复杂,或者由于任何原因(如垃圾回收或其他后台活动)而延迟了某次执行,则scheduleAtFixedRate方法将快速连续地出现两次或更多的执行,从而使后续执行能够“追赶上来”;而schedule方法的后续执行也将被延迟。所以,在长期运行中,scheduleAtFixedRate执行的频率将正好是指定周期的倒数,schedule 执行的频率一般要稍慢于指定周期的倒数。
scheduleAtFixedRate 效率总体上高于schedule
分享到:
相关推荐
Java定时任务schedule和scheduleAtFixedRate的异同
主要为大家详细介绍了java中timer的schedule和scheduleAtFixedRate方法区别,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
NULL 博文链接:https://michael1990.iteye.com/blog/2113141
在Java中,Timer和TimerTask是两个经常用来实现定时器的类。这两个类使用起来非常方便,可以完成我们对定时器的绝大多数需求。 Timer是一种定时器工具,用来在一个后台线程计划执行指定任务,并可以按计划一次或反复...
调度可以用 Timer 【调用 schedule() 或者 scheduleAtFixedRate() 方法实现】或者 ScheduledExecutorService 【结合工作中其它的需求,笔者选用此】 ScheduledExecutorService的初始化(线程池):
用Java编写银行业务调度系统,附主类: package com.isoftstons.interview.bank; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class Mainlass { public Mainlass() {...
调用scheduleAtFixedRate()方法或者scheduleWithFixedDelay()方法时,会向DelayQueue添加一个实现了RunnableScheduledFuture接口的ScheduledFutureTask
定时删除文件,导入库类有Timer类,TimeTask类,运用的函数有:scheduleAtFixedRate()。
scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1,2, TimeUnit.SECONDS); super.onStart(); } @Override protected void onStop() { //当Activity不可见的时候停止切换 ...
timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { Message message=new Message(); message.what=1; handler.sendMessage(message); } }, 1000,5000); 2.在线程中创建Handle
串行执行器服务 ScheduledExecutorService 的测试实用程序实现 允许测试如下代码: ... service.scheduleAtFixedRate(new Runnable() { @Override public void run() { count++; bar.doWhatever(); } },
timer.scheduleAtFixedRate(new TimerTask() { int j=0; int i=0; @Override public void run() { if(over==true){ return; } handler.sendEmptyMessage(kPostInvalidate); i=i+...