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);
}
}
- Spring MVC项目启动时在容器加载完毕后插入一个定时任务
- spring mvc 定时任务
- spring mvc 定时任务
- spring mvc定时任务
- Tomcat启动完毕后启动方法任务
- Tomcat启动完毕后启动方法任务
- Spring quartz 任务调度器 启动加载,定时加载
- spring加载定时任务
- 如何避免Docker容器启动脚本运行后自动退出——一个cron定时任务docker镜像方案
- 项目启动定时任务
- Spring的定时任务@Scheduled,部署后执行加载两次
- Spring项目定时任务
- 项目启动后开启定时任务方法-->ServletContextListener
- 项目启动后开启定时任务方法-->InitializingBean
- Spring MVC执行定时任务
- java定时任务 spring mvc
- Quartz定时任务在Spring MVC 中的实现
- Quartz定时任务在Spring MVC 中的实现
- 初探box-decoration-break
- Linux Centos apache 图片不显示解决办法
- Struts Problem Report Struts has detected an unhandled exception:
- Change the value of "Maximum number of concurrent connections" about SQL Server 2012
- Javascript异步编程的4种方法
- Spring MVC项目启动时在容器加载完毕后插入一个定时任务
- 解决web站点中文乱码问题
- 分针网—IT教育: nodeJS新建一个项目及代码详解
- ResourceBundle.getBundle读取资源文件的路径
- android:利用jxl从excel中读取文件
- 推荐一款华为最新的自动化代码检查工具
- for in数组遍历的坑
- c++运算符重载总结
- 微信小程序免费https证书报错https证书无效