繁体   English   中英

何时关闭ScheduledExecutorService?

[英]When to shutdown 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());
            }
        }
    }

我不确定何时或是否应该调用执行程序的shutdown方法。 我使用的是JEE5,因此不确定是否简单地取消部署应用程序即可自动执行关闭操作,或者是否浪费大量时间并创建了大量的线程而不杀死它们。

-编辑-

为了防万一,我将添加更多信息。

整个应用程序都是一个RESTful Web应用程序,使用Jersey作为ServletContainer。

你说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进行实现。 在这里写了这样的答案,这是相同的想法,它确实适用于这里。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM