ScheduledExecutorService擴充了ExecutorService接口,提供時間排程的功能。
schedule(Callable<V> callable, long delay, TimeUnit unit) 建立并執行在給定延遲後啟用的 ScheduledFuture。 |
schedule(Runnable command, long delay, TimeUnit unit) 建立并執行在給定延遲後啟用的一次性操作。 |
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnitunit) 建立并執行一個在給定初始延遲後首次啟用的定期操作,後續操作具有給定的周期;也就是将在 initialDelay 後開始執行,然後在initialDelay+period 後執行,接着在 initialDelay + 2 * period 後執行,依此類推。 |
scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,TimeUnit unit) 建立并執行一個在給定初始延遲後首次啟用的定期操作,随後,在每一次執行終止和下一次執行開始之間都存在給定的延遲。 |
schedule方法被用來延遲指定時間來執行某個指定任務。如果你需要周期性重複執行定時任務可以使用scheduleAtFixedRate或者scheduleWithFixedDelay方法,它們不同的是前者以固定頻率執行,後者以相對固定頻率執行。
不管任務執行耗時是否大于間隔時間,scheduleAtFixedRate和scheduleWithFixedDelay都不會導緻同一個任務并發地被執行。唯一不同的是scheduleWithFixedDelay是目前一個任務結束的時刻,開始結算間隔時間,如0秒開始執行第一次任務,任務耗時5秒,任務間隔時間3秒,那麼第二次任務執行的時間是在第8秒開始。
ScheduledExecutorService的實作類,是ScheduledThreadPoolExecutor。ScheduledThreadPoolExecutor對象包含的線程數量是沒有可伸縮性的,隻會有固定數量的線程。不過你可以通過其構造函數來設定線程的優先級,來降低定時任務線程的系統占用。
特别提示:通過ScheduledExecutorService執行的周期任務,如果任務執行過程中抛出了異常,那麼過ScheduledExecutorService就會停止執行任務,且也不會再周期地執行該任務了。是以你如果想保住任務都一直被周期執行,那麼catch一切可能的異常。
package test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestScheduledThreadPoolExecutor {
private static SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
public static void main( String [] args) { //ScheduledExecutorService exec=Executors.newScheduledThreadPool(1); ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor( 1);
exec . scheduleAtFixedRate( new Runnable() {
public void run() {
System . out . println( format . format( new Date()));
}
}, 1000 , 5000 , TimeUnit . MILLISECONDS);
//開始執行後就觸發異常,next周期将不會運作
exec . scheduleAtFixedRate( new Runnable() {
public void run() {
System . out . println( "RuntimeException no catch,next time can't run");
throw new RuntimeException();
}
}, 1000 , 5000 , TimeUnit . MILLISECONDS);
//雖然抛出了運作異常,當被攔截了,next周期繼續運作
exec . scheduleAtFixedRate( new Runnable() {
public void run() {
try {
throw new RuntimeException();
} catch ( Exception e ){
System . out . println( "RuntimeException catched,can run next");
}
}
}, 1000 , 5000 , TimeUnit . MILLISECONDS);
exec . scheduleWithFixedDelay( new Runnable() {
public void run() {
System . out . println( "scheduleWithFixedDelay:begin," + format . format( new Date()));
try {
Thread . sleep( 2000);
} catch ( InterruptedException e) {
e . printStackTrace();
}
System . out . println( "scheduleWithFixedDelay:end," + format . format( new Date()));
}
}, 1000 , 5000 , TimeUnit . MILLISECONDS);
exec . schedule( new Runnable() {
public void run() {
System . out . println( "The thread can only run once!");
}
}, 5000 , TimeUnit . MILLISECONDS);
}
}
本文出自 “ketqi” 部落格,請務必保留此出處http://ketqi.blog.51cto.com/1130608/687681