2017-01-01 27 views
1

我有一個計劃執行服務,每X秒執行一個方法。是否可以有一個方法可以強制Scheduled Execution Service跳過執行延遲中的剩餘時間並立即調用該方法。或者我可以簡單地停止並立即重新啓動它?我可以跳過當前執行延遲還是立即重新啓動預定執行服務?

這裏是我的代碼:

Runnable runnable = new Runnable() { 
    public void run() { 

     callTheFunction(); 

    } 
}; 

ScheduledExecutorService executor; 
executor = Executors.newScheduledThreadPool(1); 
executor.scheduleAtFixedRate(Runnable, 0, 5, TimeUnit.SECONDS); // 0 sec delay | 5 sec repeat 

public void restartTheExecutor() { 
    // code to restart it or skip the remaining time. 
} 

這是我的更新和工作代碼,它包含必須設置爲false,第一次運行的參數一個布爾值。

public void restartExecutor(View v, boolean stopRequiered) { 

    if (stopRequiered) { 
     scheduled.cancel(true); 
    } 

    Runnable runnable = new Runnable() { 
     public void run() { 
      nextExpression(); 
     } 
    }; 

    ScheduledExecutorService executor; 
    executor = Executors.newScheduledThreadPool(1); 
    scheduled = executor.scheduleAtFixedRate(runnable, 0, 3, TimeUnit.SECONDS); // 0 sec delay | 5 sec repeat 

} 

回答

2

這是不可能強制執行預定功能立即運行ScheduledExecutorService

但是,對於第二個問題,答案是肯定的。您可以隨時移除任何預定功能,並按需要運行它。你需要單獨雖然參考功能:

Runnable runnable = new Runnable() { 
    public void run() { 
     callTheFunction(); 
    } 
}; 

ScheduledExecutorService executor; 
executor = Executors.newScheduledThreadPool(1); 
Future<?> scheduled = executor.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.SECONDS); // 0 sec delay | 5 sec repeat 

// cancel and run immediately: 
scheduled.cancel(true); 
runnable.run(); 

注意,這cancel()將取消不僅是下一個(或電流)的運行,而且所有未來運行。所以你必須再次重新安排:

// reassigned scheduled to next runs: 
scheduled = executor.scheduleAtFixedRate(runnable, 5, 5, TimeUnit.SECONDS); // 5 sec delay | 5 sec repeat 

或者根本都用0延遲和5S異步運行的步驟再重複:

scheduled.cancel(true); 
scheduled = executor.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.SECONDS); // 0 sec delay | 5 sec repeat 
+0

謝謝,完美的作品 – james

+0

我到運行中有一點錯誤,我在一個函數中運行你的代碼,它只運行一次並停止。 – james

+1

@james:正如我寫的,你需要重新安排時間,因爲'cancel()'取消所有將來的運行,而不僅僅是下一次運行。查看完整答案(我用另一個解決方案更新)。 –