2017-02-21 83 views
2

我正尝试在java中编写守护程序服务作业。这项服务将每分钟运行一次。Java ExecutorService无限循环作业

但我不能通过使用ExecutorService实现这一点,我不知道这是否是正确的方式。下面是我的代码片段:

public void startService() { 
    try { 
     ExecutorService service = Executors.newFixedThreadPool(3); 

     for (;;) { 
      service.submit(new Service1()); // this will send some set of emails 
      service.submit(new Service2()); // this will send some set of emails 
      service.submit(new Service3()); // this will send some set of sms 
     } 
     service.shutdown(); // It says Unreachable code so when should i shutdown the service 
     service.awaitTermination(1, TimeUnit.MINUTES); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 

回答

3

for loop没有一个结束条件for(;;),并没有break语句。

所以所有的代码这个循环是如果当然无法访问。


你必须等待1分钟内,而不是之后(如您的循环后的代码将永远不会被拼命地跑)。

保持你的synthax,我想这应该是:

for (;;) { 
    service.submit(new Service1()); // this will send some set of emails 
    service.submit(new Service2()); // this will send some set of emails 
    service.submit(new Service3()); // this will send some set of sms 
    service.shutdown(); 
    service.awaitTermination(1, TimeUnit.MINUTES); 
} 
+0

是的,它没有结束工作。它会每分钟运行一次。你能说说怎么做到这一点。 – DEADEND

1

此位置:

for (;;) { 
     service.submit(new Service1()); // this will send some set of emails 
     service.submit(new Service2()); // this will send some set of emails 
     service.submit(new Service3()); // this will send some set of sms 
    } 

是一个无限循环;它会不断向你的线程池中提交新的工作。非一次每分钟,但一次每次迭代。你必须缓慢下来你的循环!

我不确定你在问什么,但你应该简单地删除那个循环结构;或更可能的,做类似的事情:

while (true) { 
    service.submit(new Service1()); // this will send some set of emails 
    service.submit(new Service2()); // this will send some set of emails 
    service.submit(new Service3()); // this will send some set of sms 
    Thread.sleep(1 minute); 
} 

或类似的东西。

+1

@GhostCat ..如果你不明白我的问题,请留下它。不要继续。 – DEADEND

+4

@GhostCat:不管怎样,你都可以锻炼你说的话。我们在这里帮助,而不是用棍棒打人。也许可以使用不同的方法。 – Paul

4

首先你需要看看ScheduledExecutorService及其实现。此服务允许您安排作业以预定义的频率运行。这是简短的答案。至于实施细节,有太多的未知数给你实际的建议。你想让你的程序在一个容器(Web或Application Server)中运行,或者作为带域名线程的独立运行?你在Unix/Linux上运行(所以可以使用Cron作业调度程序)还是Windows?其中一个调度程序选项可能是quartz-scheduler。我希望这有帮助。