2014-03-28 47 views
0

我正在开发一个应用程序,需要按特定顺序逐一执行网络任务,并在每次执行之间的特定时间执行一次。循环执行后台网络任务,同时能够取消整个循环

我试图用AsyncTask和TimerTask来实现这个。

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

TimerTask在某种程度上工作,但它非常笨重。尝试取消TimerTask中间操作已被证明是相当困难的,而且我一直在运行两个版本的任务。当我试图将TimerTask分成五个较小的TimerTasks(每个需要完成的操作之一)时放大了这个问题。

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

回答

0
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; 
    } 
} 

下面是一个例子Runnable接口,将与RunnableQueue工作:

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(); 
     } 
    } 
};