在 J2EE 項目中,常需後台定時執行業務邏輯(如建索引、發郵件、寫日志)。本文介紹基於 JDK 原生 Timer/TimerTask + ServletContextListener 的輕量級方案。
DisplayDateTaskpublic class DisplayDateTask extends TimerTask {
@Override
public void run() {
try {
System.out.println(new Date()); // 定時打印當前時間
} catch (Exception e) {
e.printStackTrace();
}
}
}
AutoRunListenerpublic class AutoRunListener implements ServletContextListener {
private Timer timer;
@Override
public void contextInitialized(ServletContextEvent sce) {
timer = new Timer(true); // 守護線程,不阻塞應用關閉
// 延遲 0ms,每 3 秒執行一次
timer.schedule(new DisplayDateTask(), 0, 1000 * 3);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
if (timer != null) {
timer.cancel(); // 銷毀時取消定時器
}
}
}
<listener>
<listener-class>com.example.autorun.AutoRunListener</listener-class>
</listener>
ServletContextListener 監聽 Web 應用生命周期contextInitialized:容器啟動 WebApp 後調用,早於 Filter/Servlet 初始化contextDestroyed:容器關閉 WebApp 前調用,晚於 Servlet/Filter 銷毀Timer(true):守護線程模式,JVM 退出時自動終止,無需手動清理原生 Timer 適合簡單場景,複雜業務建議遷移成熟調度框架。