- Java code
import java.util.Timer;import java.util.TimerTask;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;public class SetTimerExecute extends TimerTask implements ServletContextListener { private Timer t = new Timer(); public void contextDestroyed(ServletContextEvent arg0) { // 服务器关闭时的动作 System.out.println("服务器停止"); t.cancel(); } public void contextInitialized(ServletContextEvent arg0) { // 服务器启动时的动作 System.out.println("服务器启动"); t.schedule(new SetTimerExecute(), 10000, 60 * 60 * 1000); } public void run() { try { System.out.println("自动执行方法"); } catch (Exception e) { e.printStackTrace(); } finally { } }}
使用定时器后,关闭tomcat时候总会报错
2011-10-25 9:33:21 org.apache.catalina.loader.WebappClassLoader clearReferencesT
hreads
严重: The web application [/jmail] appears to have started a thread named [Timer
-1] but has failed to stop it. This is very likely to create a memory leak.
2011-10-25 9:33:21 org.apache.coyote.http11.Http11AprProtocol destroy
信息: Stopping Coyote HTTP/1.1 on http-8888
2011-10-25 9:33:21 org.apache.coyote.ajp.AjpAprProtocol destroy
信息: Stopping Coyote AJP/1.3 on ajp-8009
请问 该如何修改代码 让tomcat能正常关闭?
关闭服务器的时候 我调用了 timer的cancel方法 但是不起作用
------解决方案--------------------
应该是又进程没挂掉~~~
试试
java.lang.Runtime
void addShutdownHook(Thread hook)
------解决方案--------------------
why use util.Timer?
why do not use javax.ejb.TimerService?
------解决方案--------------------
servlet是基于tomcat的,tomcat都关了,肯定有错
------解决方案--------------------
应该是可以的,contextDestroyed方法被调用了么,这个方法的那几行字打印了么
------解决方案--------------------
更好的处理方式是:单独实现TimerTask的子类,单独实现contextlistener的监听器类。然后在contextListener监听器实例中创建一个实例字段来引用TimerTask实例,这样在destory时就不存在上面的哦错误
------解决方案--------------------
把做任务的类,单独写一个。不要写到监听类里.
------解决方案--------------------