2011-06-22 51 views
0

我想先安排一項任務經常發生,然後再減少一次。我寧願不爲這個添加一個依賴到Quartz。優雅的非線性任務調度?

在標準的Java庫,我已經拿出最好的是一系列的一次性任務,其次是頻率較低的線性時間表:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); 
    myRunnable = new MyRunnable(); 
    executor.schedule(myRunnable, 0, TimeUnit.SECONDS); 
    executor.schedule(myRunnable, 5, TimeUnit.SECONDS); 
    executor.schedule(myRunnable, 10, TimeUnit.SECONDS); 
    executor.schedule(myRunnable, 15, TimeUnit.SECONDS); 
    executor.schedule(myRunnable, 30, TimeUnit.SECONDS); 
    executor.schedule(myRunnable, 45, TimeUnit.SECONDS); 
    executor.scheduleWithFixedDelay(myRunnable, 60, 300, TimeUnit.SECONDS); 

有沒有更好的方法?

回答

5

您可以讓任務觸發其下一次執行,並且每次完成後都會增加一些「等待秒數」?

+0

哦,我以前做過。感謝您的提醒。 –

2

進行了擴展,@dcn建議什麼,你可以寫一個委託的類,它的調度:

public class NonLinearScheduling { 

    public static void taperingOffSchedule(final ScheduledExecutorService executor, 
             final Runnable task, 
             final long initialDelay, 
             final TimeUnit unit, 
             final double decayMultiplier) { 
    assert initialDelay > 0; 
    assert decayMultiplier > 1.0; 
    Runnable repeater = new Runnable() { 
     double nextDelay = initialDelay; 
     public void run() { 
      task.run(); 
      nextDelay *= decayMultiplier; 
      executor.schedule(this, (long) nextDelay, unit); 
     } 
    }; 
    executor.schedule(repeater, initialDelay, unit); 
    } 
} 

還要注意,而不是repeater是匿名Runnable的,它可以成爲公知類型允許將來的調度被取消等:

public interface Repeater extends Runnable { 
    void stopRepeating(); 
} 


public class NonLinearScheduling { 
    public static Repeater taperingOffSchedule(...) { ... } 

    private static class NonLinearRepeater implements Repeater { 
    private final AtomicBoolean _repeat = new AtomicBoolean(true); 

    public void stopRepeating() { 
     _repeat.set(false); 
    } 

    public void run() { 
     if (_repeat.get()) { 
     ...   
     } 
    } 
    } 
} 
+0

謝謝,好主意! –