`

Java 定时器(1)

阅读更多
Java定时器(java.util.Timer)有定时触发计划任务的功能,通过配置定时器的间隔时间,在某一间隔时间段之后会自动有规律的调用预先所安排的计划任务(java.util.TimerTask)


必须能让定时器宿主的存活期为整个Web工程生命期,在工程启动时能自动加载运行。结合这两点,跟Servlet上下文有关的侦听器就最合适不过了,通过在工程的配置文件中加以合理配置,会在工程启动时自动运行,并在整个工程生命期中处于监听状态。


引用 schedule和scheduleAtFixedRate



package cn.rg.demo.test;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TestTimer {
/**
* 测试JDK Timer的执行
*/
public static void main(String[] args) {
Timer t = new Timer();

// 在5秒之后执行TimerTask的任务
t.schedule(new TimerTask() {
public void run() {
System.out.println("0001");
}
}, 5* 1000);

// 在Date指定的特定时刻之后执行TimerTask的任务
/* Date d1 = new Date(System.currentTimeMillis() + 1000);
t.schedule(new TimerTask() {
public void run() {
System.out.println("this is task you do2");
}
}, d1);*/

// 在Date指定的特定时刻之后,每隔1秒执行TimerTask的任务一次
Date d2 = new Date(System.currentTimeMillis() + 1000);
t.schedule(new TimerTask() {
public void run() {
System.out.println("003");
}
}, d2, 3 * 1000);

}
}



schedule和scheduleAtFixedRate的区别在于,如果指定开始执行的时间在当前系统运行时间之前,scheduleAtFixedRate会把已经过去的时间也作为周期执行,而schedule不会把过去的时间算上


仔细研读java api,发现:

schedule(TimerTask task, long delay)的注释:Schedules the specified task for execution after the specified delay。大意是在延时delay毫秒后执行task。并没有提到重复执行

schedule(TimerTask task, long delay, long period)的注释:Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay。大意是在延时delay毫秒后重复的执行task,周期是period毫秒。

这样问题就很明确schedule(TimerTask task, long delay)只执行一次,schedule(TimerTask task, long delay, long period)才是重复的执行。


在调scheduleAtFixedRate方法执行任务时,启动服务器任务重复连续执行两次,而用schedule则执行一次
timer.schedule(new EnterAction(), time, 1000 * 60 * 60 * 1); //执行一次

timer.scheduleAtFixedRate(new EnterAction(), time, 1000 * 60 * 60 * 1);//执行两次
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics