2017-02-21 2 views
2

Javaでデーモンサービスジョブを作成しようとしています。このサービスは毎分実行されます。Java ExecutorService無限ループジョブ

私はExecutorServiceを使用してこれを実装することはできませんが、これが正しい方法であるかどうかわかりません。以下は私のコードスニペットです:for(;;)、無break文:

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終了条件を持っていません。

もちろん到達不能のであれば、すべてのコード後にこのループがあります。


あなたは(あなたのループの後のコードがrunnedされることはありませんよう)ではないの後、ループ内で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 
    } 

は無限ループです。あなたのスレッドプールに新しい仕事を提出し続ける...常に。 1回につきですが、1回につき回です。あなたは遅いあなたのループをダウンする必要があります!

あなたが何を求めているのか分かりませんが、そのループ構成を削除するか、またはもっと可能性があります:

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ジョブスケジューラを使用することができますか?スケジューラオプションの1つはquartz-schedulerです。私はこれが役立つことを願っています

関連する問題