java.util.concurrent.ScheduledExecutorService:是否可以在启动另一个服务之前等待服务完成?

时间:2018-05-28 07:19:41

标签: java timer scheduledexecutorservice

我在我的web.xml中设置了2个服务,我为每个服务创建了这样的服务:

public class MyScheduler implements ServletContextListener {

    private ScheduledExecutorService scheduledExecutorService = null;

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        if ((scheduledExecutorService == null) || (!scheduledExecutorService.isTerminated())) {
            scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
            scheduledExecutorService.scheduleAtFixedRate(new MyScheduledTimer(), 0, 15, TimeUnit.DAYS);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        try {
            scheduledExecutorService.shutdown();
        } catch (Exception ex) {
        }
    }
}

class MyScheduledTimer extends TimerTask {

    {
        try {
            MyEjb ejbObject = (InterfaceEjb) new InitialContext().lookup("java:global/project/MyEjb");

        } catch (NamingException ex) {
            Logger.getLogger(MyScheduler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(MyScheduler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run() {
        //my code to run with ejbObject...
    }
}

我想运行第一个服务来启动我的应用程序,等待该服务完成并运行第二个服务。可能吗?

1 个答案:

答案 0 :(得分:0)

如果你想使用更具体的东西 - 你可以使用CountDownLatch作为例子。创建

CountDownLatch latch = new CoundownLatch(1); 

第一项服务将在完成工作后致电countDown()

//service1
public void run(){
    doSmthng();
    latch.countDown();
}

第二个服务将等到锁存计数器不等于0。

//service2
public void run(){
    latch.await();
    doSmthngElse();
}