我有一个需要启动计划执行的单例。这是代码:
public enum Service{
INSTANCE;
private Service() {
startAutomaticUpdate();
}
private void startAutomaticUpdate() {
try {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(new AutomaticUpdate(), 0, 15, TimeUnit.MINUTES);
} catch (Exception e) {
LOG.error(e.getMessage() + "Automatic update not working: ");
}
}
//Makes a call to a webservice that updates a static variable.
private void getTemplateNames(){...}
private class AutomaticUpdate implements Runnable {
public AutomaticUpdate() {
}
@Override
public void run(){
try{
getTemplateNames();
}catch(Exception e){
LOG.error("Error in automatic update: "+e.getMessage());
}
}
}
我不确定何时或是否应该调用执行器的关闭方法。我正在使用 JEE5,所以我不确定简单地取消部署应用程序是否会自动执行关闭,或者我是否搞砸了大时间并创建了荒谬的线程数量而不是杀死它们。
-编辑-
为了以防万一,我会添加更多信息。
整个应用程序是一个使用 Jersey 作为 ServletContainer 的 RESTful Web 应用程序。
最佳答案
你说的是JEE5?为什么要重新发明轮子?
只需使用@Schedule
和@Startup
创建一个EJB
@Singleton
@Startup
public class TaskSingleton {
@Schedule(second = "0", minute = "*/15", hour = "*")//This mean each 15:00 minutes
public void getTemplateNames() {
// YOUR TASK IMPLEMENTATION HERE
}
}
不,你不是指 JEE5 投诉服务器。 :(
使用 ServletContextListener 进行实现。我写了一些类似的答案 here ,这是同样的想法,它确实适用于这里。
关于java - 何时关闭 ScheduledExecutorService?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31036626/