一、java自带的 Timer
示例
class-1
import javax.servlet.ServletContextListener;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
public class MyListener implements ServletContextListener {
private Timer timer = null;
public void contextInitialized(ServletContextEvent event) {
timer = new Timer(true);
timer.schedule(new MyTask(), 0, 1000*10);
}
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
}
}
class-2
import java.util.TimerTask;
public class MyTask extends TimerTask{
public MyTask() {
System.out.println("new timer "+System.currentTimeMillis());
}
public void run(){
System.out.println(" timer is running ,time is "+System.currentTimeMillis());
}
}
配置
<listener>
<listener-class>MyListener</listener-class>
</listener>
二、开源
quartz
本文介绍如何使用Java内置的Timer类实现定时任务,并展示了通过Servlet容器监听器启动和销毁定时任务的具体示例。此外还提到了Quartz等开源定时任务框架。
3430

被折叠的 条评论
为什么被折叠?



