2016-04-11 1 views
1

私は自分のアプリケーションのバックグラウンドタスクを継続的に実装しようとしています。 私はScheduledExecutorServiceクラスを使用しています。 私は2つのサービスを持っていますService AService Bは両方とも、一定の時間間隔の後に常に実行されるタスクを持っています。私はこれを次のように使用しましたService AService BScheduledExecutorService。 2つの別々のサービスでいくつかの時間間隔の後に2つのタスクを実行する方法

これは両方のサービスクラスで共通のコードです。

Runnable postNotificationRunnable = new Runnable() { 
      @Override 
      public void run() { 
      // statements here} 
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); 
    scheduledExecutorService.scheduleAtFixedRate(postNotificationRunnable, 0, 1000, TimeUnit.SECONDS); 

私はアプリの両方のサービスが開始されるが、他の1が実行されないService A実行の唯一のみscheduledExecutorServiceを実行すると問題があります。私は間違って何をしていますか? P.私は初めてScheduledExecutorServiceを使用しています。

答えて

0

ScheduledExecutorServiceは、指定したのレート(あなたの場合は1000秒)よりも時間がかかる場合、タスクが完了するのを待ちます。それぞれのJavadocを見て:このタスクのいずれかの実行はその期間よりも長くかかる場合

[...]、その後、後続の実行が遅れて開始することができますが、同時に実行されません。あなたのサービスは(したがって、アプリケーションがシャットダウンされるまで実行し続ける)デーモンのように動作するように見えるので

、あなたはこのようにそれを行うことができます:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); 
ExecutorService pool = Executors.newCachedThreadPool(); 

scheduler.scheduleAtFixedRate(new Runnable() { 
    @Override 
    public void run() { 
     pool.execute(postNotificationRunnable); 
    } 
}, 0L, 1000L, TimeUnit.SECONDS); 

は、単にあなたのサービスの実際の実行を委任するschedulerには影響しない別のpoolがあります。

関連する問題