我想在运行在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.发布于 2013-02-21 00:54:41
here已经讨论了使用计时器任务的另一种选择。使用ScheduledThreadpoolExecutor类可能会帮助解决在上传新版本时仍有多个线程运行的问题,但是我不能肯定它会这样做。由于javadoc中讨论的各种原因,该类也比Timer类更受欢迎。
发布于 2013-02-21 01:05:01
还要注意,由于Timer使用单个线程,如果它的一个实例花费的时间太长,那么其他实例的准确性可能会受到影响。
最后,如果Timer抛出未检查的异常,则终止Timer线程。
由于这些(和其他)原因,它在很大程度上已经失宠-- ScheduledThreadPoolExecutor是一个更好的选择。
同样,容器中的用户管理线程可能会很棘手。
您可以尝试通过cron调度可重复的任务,也许它可以定期调用专用的servlet (或类似的)。
发布于 2013-02-21 05:07:23
使用ServletContextListener在web应用程序启动和停止时启动和停止计时器。
https://stackoverflow.com/questions/14985191
复制相似问题