萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Java Timer 與 TimerTask 完整教學:定時任務排程、固定頻率與優雅關閉

核心類別

  • 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 點)

基礎範例:延遲 1 秒啟動,每 2 秒執行一次

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); }
    }
}

關鍵最佳實務

  1. Timer 是單執行緒: 任務執行時間過長會阻塞後續任務。耗時任務請在 run() 內另開執行緒或使用 ScheduledExecutorService。
  2. 異常會殺死 Timer: run() 拋出未捕獲異常會導致 Timer 執行緒終結,**所有排程任務永久停止**。務必在 run() 內 try-catch 吞掉異常或記錄日誌。
  3. 優雅關閉: 呼叫 timer.cancel() 會拒絕新任務、等待執行中任務結束、喚醒執行緒結束。timer.purge() 可清除已取消任務佇列釋放記憶體。
  4. 避免使用 System.in.read() 阻塞主執行緒: 實務上應用 ScheduledExecutorService + ShutdownHook 或框架(Spring @Scheduled、Quartz)。

現代替代方案:ScheduledExecutorService (JDK 5+)

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 取得結果、取消單一任務。
  • 標準化關閉流程,生產環境**強烈建議**使用此 API 取代 Timer。

總結: Timer 適合簡單教學、輕量級工具、單執行緒足夠的場景。企業級應用請直接使用 ScheduledExecutorService 或成熟排程框架(Quartz、Spring Task、XXL-JOB)。

copyright © 萬盛學電腦網 all rights reserved