我想在 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.
有什么更好的方法来实现或避免这种情况?