首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

定时器应用Timer,timerTask

2012-12-23 
定时器使用Timer,timerTask1.每隔10分钟触发web.xmllistenerlistener-classcom.listener.GoodsListene

定时器使用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();
}



}


热点排行