scheduleAtFixedRate与schedule的区别主要是基准时间点以及第一次执行时执行的次数
timer.scheduleAtFixedRate(TimerTask, startTime, period): 如果执行时间executeTime>startTime,则一执行就会从startTime开始(startTime时就会跑一次),每隔peroid跑TimerTask。以startTime为起点。
public class TimerTest {
public static void main(String args[]) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("do task at "+new Date());
}
}, f.parse("2014-04-15 17:20:00"), 10 * 1000);
}
}
执行时间是17:28:01,执行结果是
do task at Tue Apr 15 17:28:01 CST 2014
do task at Tue Apr 15 17:28:01 CST 2014
do task at Tue Apr 15 17:28:01 CST 2014
do task at Tue Apr 15 17:28:01 CST 2014
do task at Tue Apr 15 17:28:01 CST 2014
do task at Tue Apr 15 17:28:01 CST 2014
do task at Tue Apr 15 17:28:01 CST 2014
//以上是开始执行时立刻执行了X次,X是从startTime开始每隔peroid时间执行一次直到executeTime.
//以下是以startTime开始每隔peroid执行一次
do task at Tue Apr 15 17:28:10 CST 2014
do task at Tue Apr 15 17:28:20 CST 2014
timer.schedule(TimerTask, startTime, period): 如果执行时间executeTime>startTime,其实基准时间已经变成executeTime,每隔peroid跑TimerTask。以executeTime为起点。(如果executeTime<startTime,则基准时间还是startTime)
同样的例子,结果是
do task at Tue Apr 15 17:28:01 CST 2014
do task at Tue Apr 15 17:28:11 CST 2014
do task at Tue Apr 15 17:28:21 CST 2014
就在executeTime执行一次,然后以executeTime为基准点每隔peroid执行一次
scheduleAtFixedRate与schedule的下一次执行时间都是上一次执行完成时间+间隔时间,只是由于第一次执行时executeTime>startTime时造成的基准时间不一致而造成的的。
另外,如果task的执行时长>间隔时长peroid, 则下一次执行时间是上一次完成时间, scheduleAtFixedRate与schedule和都是一样的。
public class TimerTest {
public static void main(String args[]) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("start do task at "+new Date());
try{
Thread.sleep(11000);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("end do task at "+new Date());
}
}, f.parse("2014-04-15 18:01:00"), 10 * 1000);
}
}
执行时间是18:01:25, 执行结果
start do task at Tue Apr 15 18:01:25 CST 2014
end do task at Tue Apr 15 18:01:36 CST 2014
//这里可以看出下次执行时间就是上次完成时间
start do task at Tue Apr 15 18:01:36 CST 2014
end do task at Tue Apr 15 18:01:47 CST 2014
start do task at Tue Apr 15 18:01:47 CST 2014
end do task at Tue Apr 15 18:01:58 CST 2014
scheduleAtFixedRate结果也是一样的