2017-02-21 85 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。我希望這有幫助。