構建一個圖形化監控平台,需同時運行多個獨立的定時任務,每個任務擁有自定義週期、調用參數(如目標服務器地址),並能實時展示運行次數、日誌輸出。本文梳理基於 Swing 的多線程調度架構與界面交互設計。
public abstract class ScheduledTask implements Runnable {
protected volatile boolean running = false;
protected long intervalMs; // 執行間隔
protected ServerConfig config; // 目標服務器配置
protected int executeCount = 0; // 執行計數
public abstract void executeTask() throws Exception;
@Override
public void run() {
while (running) {
try { executeTask(); executeCount++; }
catch (Exception e) { logError(e); }
sleepInterval();
}
}
}
// 任務線程中更新計數
SwingUtilities.invokeLater(() -> countLabel.setText(String.valueOf(++executeCount)));
// 配置變更從 EDT 發布到任務線程
task.setIntervalMs(newInterval);
task.setConfig(newConfig);
採用 ScheduledExecutorService 替代 Timer,支持固定延遲(scheduleWithFixedDelay)與固定頻率(scheduleAtFixedRate)兩種模式,配合 TimeUnit 靈活換算用戶輸入的「每 30 秒」「每小時」等週期。
自定義 LogHandler 繼承 java.util.logging.Handler,publish() 方法中 SwingUtilities.invokeLater 追加到 JTextArea,並自動滾動到底部。設置 setLevel(Level.ALL) 捕獲所有級別日誌。
使用 Preferences API(java.util.prefs.Preferences)自動保存各任務的間隔、服務器地址等參數到系統註冊表/Linux 隱藏文件,下次啟動自動恢復。

Swing 雖非現代 Web 技術棧,但在內網桌面運維工具、嵌入式設備管理端等場景仍具優勢。通過「任務線程隔離 + EDT 安全更新 + Preferences 持久化」三板斧,可快速構建穩定易用的多定時任務監控台。完整代碼可參考作者 CSDN 博客(s00n/jasea@sina.com)。