1.web.xml配置监听
2.定时器
3.定时执行任务实体
<listener>
<listener-class>com.promgr.commonmodule.MyTimer</listener-class>
</listener>
2.定时器
package com.promgr.commonmodule;
import java.util.Calendar;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyTimer implements ServletContextListener {
public static final long DAY = 86400000;
//定时器
private Timer timer;
/**
* 在Web应用结束时停止任务
*/
public void contextDestroyed(ServletContextEvent sce) {
timer.cancel();//定时器销毁
}
/**
* 在Web应用启动时初始化任务
*/
public void contextInitialized(ServletContextEvent sce) {
//定义定时器
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1);
c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
timer = new Timer(true);
//MyTimeTask myTask=new MyTimeTask(); //定时器执行的任务
MyTimeTask myTask=new MyTimeTask(sce.getServletContext());//myTask中要用到context
timer.schedule(myTask, 5000, 10000); // 启动后5s执行,每隔10s执行
}
}
3.定时执行任务实体
package com.promgr.commonmodule;
import java.util.Calendar;
import java.util.TimerTask;
/**
* @author yums
* 2014-1-24
*/
public class MyTimeTask extends TimerTask {
private ServletContext servletContext;
public MyTimeTask(){
}
public MyTimeTask(ServletContext servletContext){
this.servletContext = servletContext;
}
/* (non-Javadoc)
* @see java.util.TimerTask#run()
*/
public void run() {
// TODO Auto-generated method stub
Calendar myCalendar=Calendar.getInstance();
int thisDay=myCalendar.get(Calendar.DATE);
int thisTime=myCalendar.get(Calendar.HOUR_OF_DAY);
System.out.println("Day======"+thisDay+" hour====="+thisTime);
XmlWebApplicationContext context = new XmlWebApplicationContext();
// 需要指定ServletContext对象
context.setServletContext(servletContext);
// 指定配置文件路径,开头的斜线表示Web应用的根目录
String[] a = {"/WEB-INF/applicationContext-th.xml","/WEB-INF/applicationContext-tzq.xml"};
context.setConfigLocations(a);
// 初始化容器
context.refresh();
System.out.println("-----1-----");
IntScheduleService scheduleService=(IntScheduleService)context.getBean("scheduleService");
Map<String, String> map = new HashMap<String, String>();
//月进度的年份动态获取 add by luogl on 2014/9/11
String ownerYear = DateUtils.getCurrentYear()+"";
map.put("ownerYear", ownerYear);
System.out.println("scheduleService==="+scheduleService);
//scheduleService.createBuildMonth(map);
}
}