2012-09-05 31 views
3
Class A 
{ 
long x; 
method1() 
    { 
    x = current time in millisecs; 
    } 
task()//want to run this after (x+30) time 
} 

我需要在(x + 30)之後運行task()。 x可能會有所不同。如果調用method1,則任務計劃在當前時間之後30之後運行,但在30個時間週期內如果再次調用method1,則我想取消先前的任務調用,並且希望在當前時間30秒後安排新的調用任務時間。我應該如何創建一個調度程序或這種類型的任務?如何在不同時間執行任務

通過scheduledthreadpoolexecutor API,但未找到此類型的調度程序。

回答

4

你問兩個問題:

1.如何安排與任意延遲一個任務?

您可以在java.util.concurrent.ScheduledThreadPoolExecutor

int delay = System.currentTimeMillis + 30; 
myScheduledExecutor.schedule(myTask, delay, TimeUnit.MILLISECONDS); 

2.如何取消已經運行的任務使用schedulemethods之一?

通過調用對從schedule方法,你叫返回Futurecancel取消任務。

if (!future.isDone()){ 
    future.cancel(true); 
} 
future = myScheduledExecutor.schedule(myTask, delay, TimeUnit.MILLISECONDS); 
1

我會記錄調用方法1的時間,我會每秒鐘檢查方法是否在30秒前調用。這樣它只會在沒有30秒的通話時執行任務。

+0

這是做這種事的唯一方法,就像每隔一秒檢查一次?如果大約每秒都有線程切換,那麼這不會成爲開銷 – vjk

+1

CPU可以每秒切換10000次。檢查每一秒都不是那麼多。您可以創建一個Future,每次調用method1()時都會取消它。這存在開銷與調用method1()次數成正比的問題。參見serg10的例子。通過投票,成本是固定的,如果它確定,當你開始這樣做時,你知道它永遠不會變得更糟。 ;) –

0

爲什麼不使用JDK的Timer類來建模您的需求。根據您的要求,您將根據需要安排計時器中的任務。

+0

我應該怎麼做 – vjk

+0

有一個週期性的任務,檢查是否設置了某個變量(意思是調用method1),並基於該任務重新調度task()以執行或者取消它。 – LordDoskias

-1
Class A 
{ 
$x; 
function method1() 
    { 
    $time = microtime(true); 
    } 
sleep($time + 30); 
task()//want to run this after (x+30) time 
} 
+0

WTF是這樣嗎?不是Java,這是肯定的。 -1 –

+0

哦,我認爲這是標記的PHP – nick

0

我認爲最簡單的方法來做你需要的是以下內容。類B是調用類。

class A { 

    public void runAfterDelay(long timeToWait) throws InterruptedException { 
     Thread.sleep(timeToWait); 

     task(); 
    } 
} 

class B { 
    public static void main(String[] args) throws InterruptedException { 
     A a = new A(); 
     // run after 30 seconds 
     a.runAfterDelay(30000); 
    } 
} 
0

使用java.util.Timer和傳遞一個回調到TimerTask計劃下一次運行。如果需要,可以使用cancel方法取消TimerTask。例如

package test; 

import java.util.Timer; 
import java.util.TimerTask; 

public class TimerTaskDemo { 
    private Timer timer = new Timer(); 
    private MyTimerTask nextTask = null; 

    private interface Callback { 
     public void scheduleNext(long delay); 
    } 

    Callback callback = new Callback() { 
     @Override 
     public void scheduleNext(long delay) { 
      nextTask = new MyTimerTask(this); 
      timer.schedule(nextTask, delay); 
     } 
    }; 

    public static class MyTimerTask extends TimerTask { 
     Callback callback; 

     public MyTimerTask(Callback callback) { 
      this.callback = callback; 
     } 

     @Override 
     public void run() { 
      // You task code 
      int delay = 1000; 
      callback.scheduleNext(delay); 
     }; 
    } 

    public void start() { 
     nextTask = new MyTimerTask(callback); 
     timer.schedule(nextTask, 1000); 
    } 

    public static void main(String[] args) { 
     new TimerTaskDemo().start(); 
    } 
}