因为学习上的要求,需要实现定时循环某个方法的功能,因此,通过学习,简单掌握了定时器(监听器)的使用。
想要实现定时的功能,我需要三个类。
第一个类:TextListerner.class继承ServletContextListener 类
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class TextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
new TimerManager();
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
第二个类:TextTimerTask类,继承了TimeTask
public class TextTimerTask extends TimerTask {
private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void run() {
try {
//在这里写你要执行的程序或调用你要执行的方法
//为了检验,可以输出执行时间,来判断定时是否成功
System.out.println("执行当前时间"+formatter.format(Calendar.getInstance().getTime()));
} catch (Exception e) {
System.out.println("-------------发生异常--------------");
}
}
}
第三个类:TimerManager类
public class TimerManager {
//时间间隔 毫秒,1秒=1000ms
private static final long PERIOD_DAY = 6000;
public TimerManager() {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime(); //第一次执行定时任务的时间
Timer timer = new Timer();
TextTimerTask task =new TextTimerTask();
//安排指定的任务在指定的时间开始进行重复的固定延迟执行。
timer.schedule(task, date, PERIOD_DAY);
}
}
最后的最后,配置一下web.xml就可以了(在idea编译器中我没有手动配置,程序自动配置了)
写自己的路径
运行一下,我定的时间是每隔6S执行一下方法,因为我没有具体的方法实现,只是输出一下执行的时间,如下图:
大功告成!!!
关于监听器的更多用法,还在学习中......