上一个任务完成后定期运行AsyncTask

问题描述:

我有一个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秒后启动任务一次。它不会像它应该那样重新执行。

请注意,我只想运行下一个任务,只有当它尚未运行并在运行5秒后运行它。

那么,为什么它没有像例外一样工作?

+0

你好CPX的结果,是的,一个解决方案是使用可运行和处理程序,但不这样做,而是使用ScheduledThreadPoolExecutor,它安全并且考虑到Android的良好性能。 https://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html –

尝试再次将您的处理程序代码放入AsyncTask的onPostExecute方法中。这样一旦完成,它将等待5秒钟再次启动。

希望它帮助;)

这是我如何用我的代码运行的方法调用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); 
} 

我分配的scheduledThreadPoolExecutor.scheduleWithFixedDelayscheduledFutureListDevices这样你就可以取消或RESUMEN只要您需要