在Java web项目springMVC框架中实现定时任务

来源:互联网 发布:苍南金融软件开发 编辑:程序博客网 时间:2024/05/21 14:09

在工作中遇到一个需求,需要定时自动执行某项功能,这就需要用到定时任务了。首先先来理一下实现思路,定时任务可以用Java.util中的timer类,把需要定时执行的任务封装到timer类的调度表中,这个timer对象需要在程序初始化时创建,这样才可以让它自动执行。那么我们就可以想到需要借用web项目启动初始化了,把这个工作放到项目初始化阶段。下面是具体的实现:

1、创建一个任务类testJob实现ServletContextListener接口

public class testJob implements ServletContextListener {}
public void contextInitialized(ServletContextEvent event) {}--重写初始化方法,把定时任务创建出来

2、testJob

Timer timer = new Timer();// 时间间隔private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;  //一天public void contextInitialized(ServletContextEvent event) {Calendar calendar = Calendar.getInstance();int year = calendar.get(Calendar.YEAR);int month = calendar.get(Calendar.MONTH);int day = calendar.get(Calendar.DAY_OF_MONTH);// 每天// 定制每天的23:30:00执行,calendar.set(year, month, day, 10, 00, 00);//calendar.set(year, month, day, 17, 22, 00);  //测试期间控制代码Date date = calendar.getTime(); // 第一次执行定时任务的时间System.out.println("执行时间:" + TimeHelper.dateToString(date, "yyyy-MM-dd HH:mm:ss"));event.getServletContext().log("定时器已启动");timer.schedule(new BackupTask(), date, PERIOD_DAY);event.getServletContext().log("已经添加任务调度表");}// 程序关闭时销毁定时器public void contextDestroyed(ServletContextEvent event) {timer.cancel();event.getServletContext().log("定时器已销毁");}
3、BackupTask()具体的代码实现

4、把实现ServletContextListener接口的初始化类配置到web.xml中,这样项目启动时才能监听到这个类,去进行初始化。

<listener><listener-class>com.job.testJob</listener-class></listener>

这样,定时任务就实现了