问题描述
今天使用Timer写定时程序,tomcat启动的时候出现以下异常信息: 严重: Error listenerStart2012-12-4 9:57:28 org.apache.catalina.core.StandardContext start严重: Context [/YGCWEB] startup failed due to previous errorsdddddd2012-12-4 9:57:28 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads严重: The web application [/YGCWEB] appears to have started a thread named [Timer-2] but has failed to stop it. This is very likely to create a memory leak. Web.xml部分配置如下: <listener> <listener-class>cn.system.util.listener.SessionListener</listener-class> </listener> <listener> <listener-class>cn.system.util.listener.ContextListener</listener-class> </listener> <listener> <listener-class>cn.business.bakefile.ListenerTimerAutoBakeFile</listener-class> </listener> <listener> <listener-class>cn.system.task.MyListener</listener-class> </listener> MyListener.java如下: package cn.system.task;import java.util.Timer;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;public class MyListener implements ServletContextListener{ private Timer myTaskTimer=null; @Override public void contextDestroyed(ServletContextEvent sce) { myTaskTimer=new Timer(true); myTaskTimer.schedule(new MyTask(),0,1000*60*60*24); } @Override public void contextInitialized(ServletContextEvent sce) { myTaskTimer.cancel(); }} MyTask.java如下:public class MyTask extends TimerTask{ public void run() { System.out.println("dddddd"); } 把web.xml的Listener去掉,启动tomcat可以正常访问,加上后就报严重信息,访问的时候报404
解决方案
@Override public void contextDestroyed(ServletContextEvent sce) { myTaskTimer=new Timer(true); myTaskTimer.schedule(new MyTask(),0,1000*60*60*24); } @Override public void contextInitialized(ServletContextEvent sce) { myTaskTimer.cancel(); }写反了contextInitialized 这是初始化 在这里创建contextDestroyed这是容器销毁 在这里cancel