2013-03-14 51 views
5

我有個問題要解決。我需要在每個請求執行中延遲運行可運行對象列表。執行帶時間差的可運行列表

說爲前我有一個像下面

List<MyReqObject> myReqObjects=new ArrayList<MyReqObject>(); 

,我已創建了線程的X數量的執行類似下面

ExecutorService execute=Executors.newFixedThreadPool(X) 

現在使用execute.invokeAl(myReqObjects);我的嘗試調用所有這些列表請求...

但我應該有這些之間的延遲。 實現這個我試過

ScheduledExecutorService scheduler =Executors.newScheduledThreadPool(1); 
scheduler.scheduleAtFixedRate(myObject, 2, 7, SECONDS); 

但在這裏我不能發送列表作爲參數,所以我可以爲7秒,2秒延遲執行相同的請求......

那麼有沒有解決辦法我的問題,請建議我

+0

您可以在可運行列表中循環以獨立地提交每個可運行列表。 – 2013-03-14 05:23:19

回答

1

創建一個定時器:

Timer timer = new Timer(); 

,如果你需要運行一次,那麼:

timer.schedule(new TimerTask() { 
    @Override 
    public void run() { 
    // Your code here 
    } 
}, 2*1000); 

反覆運行:

timer.scheduleAtFixedRate(new TimerTask() { 
    @Override 
    public void run() { 
    // Your code here 
    } 
}, 2*1000); 

看到Timer和TimerTask here

0

你可以做一個Runnable這是您的Runnable名單的包裝一些代碼示例,並跟蹤的是什麼發送。然後將該單個Runnable作爲調度程序的對象。

public class RunnableList implements Runnable { 

    private List<Runnable> runList = Collections.synchronizedList(
                new ArrayList<Runnable>()); 

    public void addRunnable(Runnable r) { 
     runList.add(r); 
    } 

    @Override 
    public void run() { 
     if(!runList.isEmpty()) { 
      runList.remove(0).run(); 
     } 
    } 
} 

本質上是一個本身就是Runnable的集合對象。請注意,如果你使用Executor路由,你可以使用Callable做類似的事情。

0

一個問題。這些Runnables是否需要在之後執行,其之前的可運行時間已經完成,或者在先前計劃後的N秒之後執行。

如果後者可以連續計劃和增加時間計數器。

int timeToWait = 2000; 

ScheduledExecutorService scheduler =Executors.newScheduledThreadPool(1); 
scheduler.scheduleAtFixedRate(myObject, 2, 7, SECONDS); 
for(int i = 1; i <= runnables.size(); i++){ 
    scheduler.schedule(r, timeToWait * i, TimeUnit.MILLISECONDS); 
} 

前者有點棘手。您需要有運行的時間表它

final int timeToWait = 2000; 
class SchedulingRunnable implements Runnable{ 
    private final Iterator<Runnable> runnables; 
    private final ScheduledExecutorService scheduler 

    public SchedulingRunnable(Iterator<Runnable> rs, ScheduledExecutorService es){..} 

    public void run(){ 
     runnables.next().run(); //assuming runnables.hasNext() 
     if(runnables.hasNext()){ 
      scheduler.schedule(this, timeToWait, TimeUnit.MILLISECONDS); 
     } 
    } 
} 
ScheduledExecutorService scheduler =Executors.newScheduledThreadPool(1); 
scheduler.schedule(new SchedulingRunnable(runnables.iterator(),schedule), timeToWait, TimeUnit.MILLISECONDS); 

這個例子有一個包裝的Runnable執行下一個可用run,然後安排下一個可用後,與指定的等待時間。