Timer为什么会一运行就执行?

来源:互联网 发布:曲家瑞画画 知乎 编辑:程序博客网 时间:2024/04/28 17:42
package com.utan.timer.test;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.Timer;public class TimerTest {public void test(){try {Timer timer = new Timer();String sToday;SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");sToday = sdf.format(new Date());SimpleDateFormat fTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date dToday = fTime.parse(sToday + " 00:20:00");Calendar cal=Calendar.getInstance(); cal.setTime(dToday);//cal.add(Calendar.DATE,1);Date doTime = cal.getTime();System.out.println(fTime.format(doTime));timer.schedule(new MyTask(), doTime, 24*60*60*1000L);} catch (Exception e) {e.printStackTrace();}}public void test2(){try {Timer timer = new Timer();String sToday;SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");sToday = sdf.format(new Date());SimpleDateFormat fTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date dToday = fTime.parse(sToday+" 00:20:00");Calendar cal=Calendar.getInstance(); cal.setTime(dToday);cal.add(Calendar.DATE,1);Date doTime = cal.getTime();timer.scheduleAtFixedRate(new MyTask(), doTime, 24*60*60*1000L);} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {TimerTest tt = new TimerTest();tt.test();tt.test2();}}

package com.utan.timer.test;import java.util.TimerTask;public class MyTask extends TimerTask{public void run() {try {String threadName = Thread.currentThread().getName();System.out.println("[" + threadName + "] executed...");} catch (Exception e) {e.printStackTrace();}}}

当使用Timer时,发现一运行就执行了,比方说设置的00:20,可现在时间是17:00,定时器却执行了定时任务一次。是因为定时器的时间总从00:00算起吗,当天这次虽然时间过了,还是要补充执行一次?

显然,很多时候,我们不需要其一重启后就执行,如果定时任务是一个比较耗时的操作,那么启动系统时,该定时任务立即执行,会严重的影响系统性能,早晨系统启动缓慢,启动后较长一段时间响应迟钝。特别碰到紧急问题,需要重启时,如此慢的操作对系统管理员来说实在是火上加油。

其实一设置00:20概念上应该是第二日来执行,当天时间已经过去了,就不需要再执行了,所以开始日期应该是第二天,而不是启动应用程序的这一天。


原创粉丝点击