最简单的Timer应用,设定每5分钟触发一个事件,但是总有一个奇怪现象:在第5、6分钟都会触发一次Timer,第10、11分钟都会触发一次Timer??!!我增加了一个static int iCCount 变量来观察状态,输出的结果也很奇怪以下是代码:MyListener.java
public class MyListener implements ServletContextListener { private Timer timer = null; public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
}
public void contextInitialized(ServletContextEvent event) {
timer = new Timer(true);
timer.schedule(new MyTask(), 0, 1000 * 60 * 5);
}
} MyTask.java
public class MyTask extends TimerTask { private static int iCCount = 0;
@Override
public void run() {
System.out.println("call at " + (new Date()));
System.out.println("now iCCount is " + ++iCCount);
} }
输出结果:
call at Tue Dec 01 20:40:26 GMT+08:00 2009
now iCCount is 1
call at Tue Dec 01 20:45:26 GMT+08:00 2009
now iCCount is 2
call at Tue Dec 01 20:46:00 GMT+08:00 2009
now iCCount is 2
call at Tue Dec 01 20:50:26 GMT+08:00 2009
now iCCount is 3
call at Tue Dec 01 20:51:00 GMT+08:00 2009
now iCCount is 3
public class MyListener implements ServletContextListener { private Timer timer = null; public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
}
public void contextInitialized(ServletContextEvent event) {
timer = new Timer(true);
timer.schedule(new MyTask(), 0, 1000 * 60 * 5);
}
} MyTask.java
public class MyTask extends TimerTask { private static int iCCount = 0;
@Override
public void run() {
System.out.println("call at " + (new Date()));
System.out.println("now iCCount is " + ++iCCount);
} }
输出结果:
call at Tue Dec 01 20:40:26 GMT+08:00 2009
now iCCount is 1
call at Tue Dec 01 20:45:26 GMT+08:00 2009
now iCCount is 2
call at Tue Dec 01 20:46:00 GMT+08:00 2009
now iCCount is 2
call at Tue Dec 01 20:50:26 GMT+08:00 2009
now iCCount is 3
call at Tue Dec 01 20:51:00 GMT+08:00 2009
now iCCount is 3
java版本,什么web容器?
我测试是正常的啊!