定时器使用Timer,timerTask
1.每隔10分钟触发
web.xml
<listener>
<listener-class>
com.listener.GoodsListener
</listener-class>
</listener>
Listener里面定义Timer
public class GoodsListener implements ServletContextListener{
private Timer daySchedule;
private static final long time_Delay=1000*60*10;//分钟
public void contextDestroyed(ServletContextEvent arg0) {
daySchedule.cancel();
}
public void contextInitialized(ServletContextEvent arg0) {
daySchedule= new Timer();
daySchedule.schedule(new GoodsTask(), time_Delay);
}
}
GoodsTask 继承TimerTask
public class GoodsTask extends TimerTask {
@Override
public void run() {
//业务处理
}
}
2.每天的6点和12点触发
public class TaskWeekSchedule implements ServletContextListener{
private Timer WeekScheduleTimer;
// 一天的毫秒数
public static final long PERIOD_DAY = 1000 * 60 * 60 * 24;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
this.
WeekScheduleTimer.cancel();
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
WeekScheduleTimer = new Timer();
//每天在固定的时间点发送信息
WeekScheduleTimer.scheduleAtFixedRate(new TaskWeek(), todayOf6(), PERIOD_DAY);
WeekScheduleTimer.scheduleAtFixedRate(new TaskWeek(), todayOf23(), PERIOD_DAY);
/*WeekScheduleTimer.schedule(new TaskWeek(), todayOf6(), PERIOD_DAY);
WeekScheduleTimer.schedule(new TaskWeek(), todayOf23(), PERIOD_DAY);
*/
}
private Date todayOf6() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,6);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
//System.out.print(CharUtil.DateToString4(cal.getTime()));
return cal.getTime();
}
private Date todayOf23() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
//System.out.print(CharUtil.DateToString4(cal.getTime()));
return cal.getTime();
}
}