java.util.Timer:排程器,單一背景執行緒循序執行所有任務。java.util.TimerTask:實作 Runnable 的抽象類別,承載任務邏輯。| 方法 | 行為 | 適用場景 |
|---|---|---|
schedule(task, delay, period) |
**固定延遲**:下次執行時間 = 上次執行**結束** + period。若任務耗時長,間隔會拉長。 | 非即時性需求、簡單週期任務 |
scheduleAtFixedRate(task, delay, period) |
**固定頻率**:下次執行時間 = 上次執行**開始** + period。若任務延遲,會嘗試追趕(連續執行補償)。 | 需精準頻率的監控、心跳、動畫幀 |
schedule(task, date) / schedule(task, date, period) |
指定首次執行絕對時間 (Date) | 定點觸發(如每天凌晨 3 點) |
import java.util.Timer;
import java.util.TimerTask;
import java.io.IOException;
public class TimerBasicDemo {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override public void run() {
System.out.println("[" + new java.util.Date() + "] 任務執行 -- " + Thread.currentThread().getName());
}
}, 1000, 2000); // delay=1s, period=2s
// 主執行緒等待使用者輸入 'c' 取消
new Thread(() -> {
try {
while (System.in.read() != 'c') {}
timer.cancel();
System.out.println("Timer 已取消,程式結束。");
System.exit(0);
} catch (IOException ignored) {}
}).start();
}
}
import java.util.Timer;
import java.util.TimerTask;
import java.io.IOException;
public class TimerAdvancedDemo {
public static void main(String[] args) {
Timer timer = new Timer();
// 任務 1:固定延遲
MyTask task1 = new MyTask("Task-1");
timer.schedule(task1, 1000, 2000);
// 任務 2:固定頻率
MyTask task2 = new MyTask("Task-2");
timer.scheduleAtFixedRate(task2, 2000, 3000);
// 控制台指令迴圈
try (var reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if ("cancel-1".equalsIgnoreCase(line)) {
task1.cancel(); // 單獨取消任務 1
System.out.println("Task-1 已取消");
} else if ("cancel-2".equalsIgnoreCase(line)) {
task2.cancel();
System.out.println("Task-2 已取消");
} else if ("cancel-all".equalsIgnoreCase(line)) {
timer.cancel(); // 取消整個 Timer,所有任務停止
System.out.println("Timer 已全部取消");
break;
} else if ("status".equalsIgnoreCase(line)) {
System.out.println("Task-1 cancelled: " + isCancelled(task1));
System.out.println("Task-2 cancelled: " + isCancelled(task2));
} else {
task1.setInfo(line); // 動態修改任務輸出內容
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
// TimerTask 的狀態欄位為 package-private,需用反射或同包裝類檢查
private static boolean isCancelled(TimerTask t) {
try {
var f = TimerTask.class.getDeclaredField("state");
f.setAccessible(true);
return f.getInt(t) == 1; // CANCELLED = 1
} catch (Exception e) {
return false;
}
}
static class MyTask extends TimerTask {
private String info = "default";
public void setInfo(String info) { this.info = info; }
@Override public void run() { System.out.println("[" + new java.util.Date() + "] " + info); }
}
}
run() 內另開執行緒或使用 ScheduledExecutorService。run() 拋出未捕獲異常會導致 Timer 執行緒終結,**所有排程任務永久停止**。務必在 run() 內 try-catch 吞掉異常或記錄日誌。timer.cancel() 會拒絕新任務、等待執行中任務結束、喚醒執行緒結束。timer.purge() 可清除已取消任務佇列釋放記憶體。System.in.read() 阻塞主執行緒: 實務上應用 ScheduledExecutorService + ShutdownHook 或框架(Spring @Scheduled、Quartz)。ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
// 固定延遲
executor.scheduleWithFixedDelay(() -> System.out.println("FixedDelay"), 1, 2, TimeUnit.SECONDS);
// 固定頻率
executor.scheduleAtFixedRate(() -> System.out.println("FixedRate"), 1, 2, TimeUnit.SECONDS);
// 關閉
executor.shutdown();
try { if (!executor.awaitTermination(5, TimeUnit.SECONDS)) executor.shutdownNow(); }
catch (InterruptedException e) { executor.shutdownNow(); }
Future 取得結果、取消單一任務。Timer。總結:
Timer適合簡單教學、輕量級工具、單執行緒足夠的場景。企業級應用請直接使用ScheduledExecutorService或成熟排程框架(Quartz、Spring Task、XXL-JOB)。