监听器实现定时任务(java定时器)
参考:https://blog.csdn.net/u011110383/article/details/73530505
java代码:
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.ibm.icu.util.Calendar;
public class TimerListener implements ServletContextListener {
private Timer timer=null;
private ServletContext context=null;
/**
* 启动任务
*/
public void contextInitialized(ServletContextEvent event){
this.context =event.getServletContext();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,18);
calendar.set(Calendar.MINUTE,38);
calendar.set(Calendar.SECOND,0);
Date time =calendar.getTime();
long period_day=24*60*60*1000;
//如果第一次执行时间小于当前时间,则将第一次执行任务的时间加一天。
if(time.before(new Date())){
time=this.addDay(time,1);
}
context.log(“定时器启动”);
timer=new Timer(true);
timer.scheduleAtFixedRate(new MyTask(this.context), time, period_day);
}
/**
* 销毁任务
*/
public void contextDestroyed(ServletContextEvent event) {
if (timer != null) {
timer.cancel();
event.getServletContext().log(“定时器销毁”);
}
}
/**
* 获取时间
* @param date
* @param num
* @return
*/
public Date addDay(Date date, int num){
Calendar startDT =Calendar.getInstance();
startDT.setTime(date);
startDT.add(Calendar.DAY_OF_MONTH, num);
return startDT.getTime();
}
//内部类定时任务
private static class MyTask extends TimerTask{
private ServletContext context=null;
public MyTask(ServletContext context){
this.context=context;
}
public void run() {
try {
WebApplicationContext webContext =WebApplicationContextUtils.getRequiredWebApplicationContext(this.context);
context.log("开始执行任务");
//获取spring容器管理的javaBean
AlarmDAO alarmDAO =(AlarmDAO) webContext.getBean("com.abchina.plantix.alarm.dao.AlarmDAO");
alarmDAO.deleteAlarm();
alarmDAO.insertCreditLimitAlarm();
context.log("任务执行结束");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
web-xml的监听器配置:
<listener>
<listener-class>
com.abchina.plantix.alarm.dao.TimerListener
</listener-class>
</listener>