我想在 Tomcat 上运行的 servlet 上每 22 分钟运行一个方法。所以我正在使用这段代码:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
update();
} catch (SQLException | NamingException | InterruptedException e1) {
e1.printStackTrace();
}
}
}, 22 * 60 * 1000, 22 * 60 * 1000);
我觉得这是一种糟糕的方法,因为我总是遇到有关计时器的错误,而且每当我上传新版本的 servlet 时,我认为它不会停止以前的计时器。然后我收到数据库连接警告。如果我重置所有内容并重新开始,那很好。
javax.naming.NameNotFoundException: Name comp is not bound in this Context
at org.apache.naming.NamingContext.lookup(NamingContext.java:770)
at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:152)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at my.app.database.DatabaseManager.connect(DatabaseManager.java:44)
at my.app.database.DatabaseManager.returnInfo(DatabaseManager.java:133)
at my.app.genParse.Generate.updateHistory(Generate.java:89)
at my.app.MyServer$1.run(MyServer.java:52)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
以及重新启动新版本时:
SEVERE: The web application [/myApp] appears to have started a thread named [Timer-7] but has failed to stop it. This is very likely to create a memory leak.
实现或避免这种情况的更好方法是什么?
最佳答案
已经讨论了使用计时器任务的替代方法 here .使用 ScheduledThreadpoolExecutor
类 MAY 有助于解决上传新版本时多个线程仍在运行的问题,但我不能肯定地说它会。由于 javadoc 中讨论的各种原因,此类也优于 Timer
类.
关于java - 计时器导致 Tomcat 服务器出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14985191/