java - 何时关闭 ScheduledExecutorService?

标签 java threadpool scheduledexecutorservice

我有一个需要启动计划执行的单例。这是代码:

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/

相关文章:

java - 覆盖分区表Bigquery的一些分区

concurrency - 高性能(但笨拙)的网络服务器

c# - 让多个线程工作并等待所有线程完成的最佳方法是什么?

java - ManagedScheduledExecutorService 任务能否在服务器重启或崩溃后继续存在?

结合两个 lambda 的 Java 实用方法?

java - 你如何在 slf4j 中格式化异常?

java - 安卓 : nonwritablechannelException and ClosedChannelException

c# - 我对C#线程池的理解正确吗?

java - 测试涉及 ScheduledExecutorService#scheduleAtFixedRate 的代码时单元测试失败

java - 如何使用 ScheduledExecutorService 安排 2 个不同的任务