Java ScheduledExecutorService定期运行

时间:2017-03-02 06:45:30

标签: java executorservice scheduledexecutorservice

我正在尝试运行一个作业[其中包含3个服务应该并行运行]每分钟。以下是我的代码段。

ExecutorService service = Executors.newFixedThreadPool(servicesMap.size());
for (Map.Entry entry : servicesMap.entrySet()) {
    service.submit(new MyService(conn, serviceID)); 
   // here serviceID is id1 id2 id3 these three job should execute parallel
}

注意:MyTask实现了Callable& servicesMap将始终是

如果我尝试使用ScheduledExecutorService,那么我无法实现它。 它表示scheduleService.schedule不接受Callable类型参数

ScheduledExecutorService scheduleService = Executors.newScheduledThreadPool(servicesMap.size());
for (Map.Entry entry : servicesMap.entrySet()) {
    scheduleService.schedule((new MyService(conn, serviceID)), 0, 60, TimeUnit.SECONDS);
}

请帮助修改ScheduledExecutorService代码以实现此目的。

1 个答案:

答案 0 :(得分:1)

您的schedule(…)调用包含的参数多于the method的参数。

但是,我不确定你究竟是在追求什么。如果您希望将来在一分钟内运行您的服务,请使用以下呼叫:

scheduleService.schedule(new MyService(conn, serviceID), 60, TimeUnit.SECONDS);

相反,如果您希望每分钟(立即开始)运行您的服务,请使用以下两个呼叫之一:

scheduleService.scheduleAtFixedRate(new MyService(conn, serviceID), 0, 60, TimeUnit.SECONDS);
scheduleService.scheduleWithFixedDelay(new MyService(conn, serviceID), 0, 60, TimeUnit.SECONDS);

关于评论中的后续问题:

  

如何制作,在一分钟内Service1服务2 Service3应该并行运行,然后下一分钟做同样的事情。

ScheduledExecutorService scheduleService = …;
Collection<Callable<Void>> services = …;
Runnable svcRunner = new Runnable() {
    @Override
    public void run() {
        Collection<Future<Void>> futures = new ArrayList<>(services.size());
        // start all services in parallel
        for (Callable<Void> service : services) {
            // any ExecutorService would do here, i.e., doesn't have to be a
            // ScheduledExecutorService
            futures.add(scheduleService.submit(service));
        }
        // wait for all services to complete
        for (Future<Void> future : futures) {
            try {
                future.get();
            } catch (InterruptedException | ExecutionException e) {
                // TODO do something meaningful
            }
        }
    }
};
// run the scheduler every minute (i.e., one minute after the last service
// has finished), starting now
scheduleService.scheduleWithFixedDelay(svcRunner, 0, 60, TimeUnit.SECONDS);

为简单起见,我已将服务存储在集合中。如果需要,您也可以每次重新创建它们。