譯者注:個(gè)人覺得用定時(shí)任務(wù)來跑垃圾回收不是很好的例子,從譯者接觸到的項(xiàng)目來看,比較常見的是用定時(shí)任務(wù)來進(jìn)行非實(shí)時(shí)計(jì)算,清除臨時(shí)數(shù)據(jù)、文件等。
在本文里,我會(huì)給大家介紹3種不同的實(shí)現(xiàn)方法:
1.普通thread實(shí)現(xiàn)
2.TimerTask實(shí)現(xiàn)
3.ScheduledExecutorService實(shí)現(xiàn)
一、普通thread
這是最常見的,創(chuàng)建一個(gè)thread,然后讓它在while循環(huán)里一直運(yùn)行著,通過sleep方法來達(dá)到定時(shí)任務(wù)的效果。這樣可以快速簡(jiǎn)單的實(shí)現(xiàn),代碼如下:
public class Task1 {
public static void main(String[] args) {
// run in a second
final long timeInterval = 1000;
Runnable runnable = new Runnable() {
public void run() {
while (true) {
// ------- code for task to run
System.out.println("Hello !!");
// ------- ends here
try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
二、用Timer和TimerTask
上面的實(shí)現(xiàn)是非常快速簡(jiǎn)便的,但它也缺少一些功能。
用Timer和TimerTask的話與上述方法相比有如下好處:
1.當(dāng)啟動(dòng)和去取消任務(wù)時(shí)可以控制
2.第一次執(zhí)行任務(wù)時(shí)可以指定你想要的delay時(shí)間
在實(shí)現(xiàn)時(shí),Timer類可以調(diào)度任務(wù),TimerTask則是通過在run()方法里實(shí)現(xiàn)具體任務(wù)。
Timer實(shí)例可以調(diào)度多任務(wù),它是線程安全的。
當(dāng)Timer的構(gòu)造器被調(diào)用時(shí),它創(chuàng)建了一個(gè)線程,這個(gè)線程可以用來調(diào)度任務(wù)。
下面是代碼:
import java.util.Timer;
import java.util.TimerTask;
public class Task2 {
public static void main(String[] args) {
TimerTask task = new TimerTask() {
@Override
public void run() {
// task to run goes here
System.out.println("Hello !!!");
}
};
Timer timer = new Timer();
long delay = 0;
long intevalPeriod = 1 * 1000;
// schedules the task to be run in an interval
timer.scheduleAtFixedRate(task, delay,
intevalPeriod);
} // end of main
}
這些類從JDK 1.3開始存在。
三、ScheduledExecutorService
ScheduledExecutorService是從Java SE 5的java.util.concurrent里,做為并發(fā)工具類被引進(jìn)的,這是最理想的定時(shí)任務(wù)實(shí)現(xiàn)方式。
相比于上兩個(gè)方法,它有以下好處:
1.相比于Timer的單線程,它是通過線程池的方式來執(zhí)行任務(wù)的
2.可以很靈活的去設(shè)定第一次執(zhí)行任務(wù)delay時(shí)間
3.提供了良好的約定,以便設(shè)定執(zhí)行的時(shí)間間隔
下面是實(shí)現(xiàn)代碼,我們通過ScheduledExecutorService#scheduleAtFixedRate展示這個(gè)例子,通過代碼里參數(shù)的控制,首次執(zhí)行加了delay時(shí)間。
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Task3 {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
// task to run goes here
System.out.println("Hello !!");
}
};
ScheduledExecutorService service = Executors
.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
}
}