Spring MVC项目启动时在容器加载完毕后插入一个定时任务

来源:互联网 发布:大连 软件招聘会 编辑:程序博客网 时间:2024/06/05 05:18

在Spring MVC中,一般项目启动时容器会自动加载,但是平时任务开发中需要在项目启动时完成一件事,而这件事却使用到了容器里的内容,此时可通过实现ApplicationListener接口的方式来完成。

一个实现了ApplicationListener接口的类,每当在一个ApplicationEvent发布到ApplicationContext(即上下文,也称为容器)时,该类就会得到通知(观察者模式),接下来以项目启动时加载一个定时任务作为例子


package com..timer;

import java.util.Date;

import java.util.List;

import java.util.Timer;

import java.util.TimerTask;

import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationListener;

import org.springframework.context.event.ContextRefreshedEvent;

import org.springframework.stereotype.Service;

//PS实现注解,为了容器扫描该类

@Service

public class TaskTimer implements ApplicationListener<ContextRefreshedEvent>{

@Autowired

private XXXService xxxService;//用到的容器内容

private Timer timer = null;

@Override

public void onApplicationEvent(ContextRefreshedEvent evt) {

if (evt.getApplicationContext().getParent() == null) {

createSitemap();//调用任务需要做的事

}

}


private void createSitemap() {

Timer timer = new Timer("createSitemap", true);

timer.schedule(new TimerTask() {

@Override

public void run() {

Date sysDateStar = new Date();

System.out.println(sysDateStar);

Date sysDateEnd = DateUtil.addDateMinut(sysDateStar, 10);

//项目启动时想要做的事

}

}, 5000, 10*60000);

}

}

0 0
原创粉丝点击