简体   繁体   English

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

[英]Periodically run AsyncTask after previous task has been finished

I have an AsyncTask which currently runs only once and takes about between 5 - 30 secs to finish. 我有一个AsyncTask,目前仅运行一次,大约需要5到30秒才能完成。

What I want to do is: 我想做的是:

1. Start the App 1.启动应用
2. Run the Task 2.运行任务
3. Wait for it to Finish. 3.等待它完成。
4. Wait for a Fixed amount of time eg 5 seconds 4.等待固定的时间,例如5秒
5. Repeat Step 2. 5.重复步骤2。

I looked around several posts which suggest using Handlers and that's how I have tried to do it: 我环顾了几条建议使用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 is a sub-class of AsyncTask in some another .java file. MyTask是另一个.java文件中AsyncTask的子类。

This only runs the task once on start-up after a delay of 5 seconds. 延迟5秒后,启动时仅运行一次任务。 It doesn't re-execute itself as it should. 它不会像应有的那样重新执行自身。

Note that I want to run the next task only if its not already running and run it 5 seconds after it. 请注意,我只想在下一个任务尚未运行时运行它,然后在它运行5秒钟后运行它。

So, why doesn't it work as excepted? 那么,为什么它不能按例外方式工作呢?

Try putting your handler code again into the onPostExecute method of the AsyncTask. 尝试再次将处理程序代码放入AsyncTask的onPostExecute方法中。 That way once it finishes it will wait 5 seconds to launch itself again. 这样,一旦完成,它将等待5秒钟再次启动自身。

hope it helps ;) 希望能帮助到你 ;)

Here is how I use my code to run a method call ListDevices every DELAY time. 这是我每隔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);
}

I am assigning the result of scheduledThreadPoolExecutor.scheduleWithFixedDelay to scheduledFutureListDevices so you can cancel it or resumen wherever you need 我将scheduledThreadPoolExecutor.scheduleWithFixedDelay的结果分配给scheduledFutureListDevices因此您可以取消它或在需要的地方恢复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM