最简单的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

解决方案 »

  1.   

    在第一个run后,有了两个Timer实例?
      

  2.   

    工程就这些了啊,还有就是web.xml的配置信息了
      

  3.   

    什么环境啊?
    java版本,什么web容器?
    我测试是正常的啊!
      

  4.   

    楼主自己再新建一个web项目,只加进这个listener试试.
      

  5.   

    发现问题了,是Tomcat的server.xml配置问题,xml中配置了两个<host>节点导致。