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

时间:2017-01-16 15:42:16

标签: java android android-asynctask handler

我有一个AsyncTask,目前只运行一次,需要5到30秒才能完成。

我想做的是:

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是另一个.java文件中的AsyncTask的子类。

这仅在启动后的一个延迟5秒后执行一次任务。它没有按照自己的意愿重新执行。

请注意,我希望仅在尚未运行的情况下运行下一个任务并在其后5秒运行它。

那么,为什么它不能作为例外工作呢?

2 个答案:

答案 0 :(得分:1)

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

希望它有所帮助;)

答案 1 :(得分:0)

以下是我如何使用我的代码在每个DELAY时间运行一个方法调用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.scheduleWithFixedDelay的结果分配给scheduledFutureListDevices,以便您可以取消它或在任何需要的地方重新开始

相关问题