【问题标题】:Execute background network tasks cyclically while being able to cancel the entire cycle循环执行后台网络任务,同时可以取消整个循环
【发布时间】:2014-03-28 04:54:27
【问题描述】:

我正在开发一个应用程序,它需要以特定的顺序一个接一个地执行网络任务,并且每次执行之间有一个特定的时间。

我尝试使用 AsyncTask 和 TimerTask 来实现它。

AsyncTask 不起作用,因为要取消它,我需要创建一个 AsyncTask 对象,但如果这样做,我将无法在完成后重新启动任务。

TimerTask 在某种程度上可以工作,但它非常笨重。事实证明,尝试取消 TimerTask 中间操作非常困难,而且我不断地运行两个版本的任务。当我尝试将 TimerTask 拆分为五个较小的 TimerTask(每个需要完成的操作一个)时,这个问题就更加严重了。

那么,有没有办法按顺序执行一组后台任务,每次执行之间有特定的时间?

【问题讨论】:

    标签: android networking timer task runnable


    【解决方案1】:
    import java.util.ArrayList;
    import java.util.Collections;
    
    public class RunnableQueue {
        ArrayList<Runnable> queue;
        Runnable[] tasks;
        boolean cancelled;
        double tag;
    
        public RunnableQueue(Runnable... tasks) {
            this.tasks = tasks;
            this.tag = Math.random();
            queue = new ArrayList<Runnable>();
            Collections.addAll(queue, tasks);
        }
    
        public void add(Runnable r) {
            queue.add(r);
        }
    
        public double getTag() {
            return tag;
        }
    
        public void addToFront(Runnable r) {
            queue.add(0, r);
        }
    
        public void next() {
            if (queue.size() > 0) {
                new Thread(queue.get(0)).start();
                queue.remove(0);
            }
        }
    
        public void stop() {
            cancelled = true;
            queue.clear();
        }
    
        public void resume() {
            if (cancelled) {
                tag = Math.random();
                cancelled = false;
                Collections.addAll(queue, tasks);
                next();
            }
        }
    
        public boolean isCancelled() {
            return cancelled;
        }
    }
    

    这是一个可与 RunnableQueue 配合使用的 Runnable 示例:

    Runnable queueTester = new Runnable() {
    
        @Override
        public void run() {
            double tag = executor.getTag();
    
            //do some background stuff here
    
            Log.i("RunnableQueue-test", "queueTester complete. Sleeping...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (executor.isCancelled()) {
                Log.i(TAG, "Boolean is false. Not continuing.");
            } else if (executor.getTag() != tag) {
                Log.i(TAG, "Tag has been updated. Not continuing.");
            } else {
                executor.add(this);
                executor.next();
            }
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2014-03-29
      • 1970-01-01
      相关资源
      最近更新 更多