2017-01-16 5 views
0

私は現在1回だけ実行されているAsyncTaskを持っており、終了するのに約5〜30秒かかります。前のタスクが完了した後、AsyncTaskを定期的に実行してください。

私がやりたいことはある:

1.アプリケーション
2.を実行し、それが終了するのをタスク
3.待ちます。
4.一定時間待機する。 5秒
5.繰り返し手順2

私はHandlersを使用することをお勧め周りにいくつかの記事を見て、それは私がそれを行うにしようとしている方法は次のとおりです。

@Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 

     final Activity activity = this; 

     final Handler handler = new Handler(); 
     handler.postDelayed(new Runnable() { 
      public void run() { 

       // Start AsyncTask 
       new MyTask(activity).execute(); 
      } 
     }, 5000); //Every 5 seconds 
    } 

MyTaskはAsyncTaskのサブクラスでありますいくつかの別の.javaファイル。

これは、起動時に5秒遅れてタスクを1回だけ実行します。必要に応じて再実行されません。

私は次のタスクがまだ実行されていない場合にのみ実行し、5秒後に実行したいとします。

なぜ、それが例外として機能しないのですか?

+0

ハローCPXを必要な場所概要できscheduledThreadPoolExecutor.scheduleWithFixedDelayscheduledFutureListDevicesの結果を代入していますが、はい、それを解決するには、実行可能とハンドラを使用することですが、ありません、代わりにScheduledThreadPoolExecutorを使用してください。これは安全で、Androidの優れたパフォーマンスを念頭に置いて設計されています。 https://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html –

答えて

1

ハンドラコードを再度AsyncTaskのonPostExecuteメソッドに入れてみてください。そうすることで、一度終了すると5秒待って再度起動します。

はそれが役に立てば幸い;)ここで

0

は、私は、メソッド呼び出しのListDevicesごとの遅延時間を実行するために自分のコードを使用する方法です。

private ScheduledFuture<?> scheduledFutureListDevices 

private void startListDevicesTaskAtRate(int rate) { 

Runnable runnable = this::requestListDeviceService; 

scheduledFutureListDevices = scheduledThreadPoolExecutor.scheduleWithFixedDelay(runnable, DELAY, rate, TimeUnit.SECONDS); 

Log.d(TAG, "STARTING LIST DEVICES TASK AT " + (rate == Constants.FAST_RATE ? " FAST " : " NORMAL ") + " RATE"); 

if (scheduledFutureListDevices != null) { 
    scheduledFutureListDevices.cancel(false); 
} 

Runnable runnable = this::requestListDeviceService; 

scheduledFutureListDevices = scheduledThreadPoolExecutor.scheduleWithFixedDelay(runnable, DELAY, rate, 
     TimeUnit.SECONDS); 
} 

私はあなたがそれをキャンセルしたり、

関連する問題