- package test;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.Locale;
- public class TimeTest {
- public static int getLocaleHour(){
- int hour = 0;
- Date date = new Date();
- Calendar calendar = Calendar.getInstance(Locale.CHINA);
- calendar.setTime(date);
- hour = calendar.get(Calendar.HOUR_OF_DAY);
- return hour;
- }
- }
HxjTimerTask.java
- package test.timer;
- import java.util.TimerTask;
- import javax.servlet.ServletContext;
- import test.TimeTest;
- public class HxjTimerTask extends TimerTask {
- private boolean isRunning = false;
- private boolean flag = true;
- private static int C_SCHEDULE_HOUR = 9;
- private ServletContext context = null;
- public HxjTimerTask(ServletContext context) {
- super();
- this.context = context;
- }
- @Override
- public void run() {
- if(!isRunning){
- if(C_SCHEDULE_HOUR == TimeTest.getLocaleHour() && flag){
- isRunning = true;
- context.log("开始执行任务");
- int i = 0;
- while(++i <= 10){
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- context.log("已经执行完任务的:"+i+"/10");
- }
- flag = false;
- isRunning = false;
- context.log("任务执行完成");
- }
- } else {
- context.log("上次任务还未执行完毕");
- }
- if(C_SCHEDULE_HOUR != TimeTest.getLocaleHour()){
- flag = true;
- }
- }
- }
HxjListener.java
- package test.timer;
- import java.util.Timer;
- import javax.servlet.ServletContextEvent;
- import javax.servlet.ServletContextListener;
- public class HxjListener implements ServletContextListener {
- private Timer timer = null;
- public void contextInitialized(ServletContextEvent event) {
- this.timer = new Timer(true);
- event.getServletContext().log("启动hxj定时器");
- timer.schedule(new HxjTimerTask(event.getServletContext()), 0,10000);
- event.getServletContext().log("已经添加任务调度表");
- }
- public void contextDestroyed(ServletContextEvent event) {
- this.timer.cancel();
- event.getServletContext().log("关闭hxj定时器");
- }
- }
TimeTest.java