Timer(boolean isDaemon) //创建一个新计时器,可以指定其相关的线程作为守护程序运行。
void schedule(TimerTask task, Date firstTime, long period) //安排指定的任务在指定的时间开始进行重复的固定延迟执行。 //第一个参数是指定任务,即TimerTask对象;第二个参数为第一次开启任务时间; 第三个参数为时间间隔,即每隔多长时间执行一次
@Component //把该对象交给Spring管理
public class ProductTimerTask extends TimerTask {
@Resource
private ProductService productService = null; //注入productService
@Resource
private CategoryService categoryService = null; //注入categoryService
private ServletContext application = null; //定义一个ServletContext对象,因为我们更新了后台数据后,需要存入application域里面
public void setApplication(ServletContext application) {
this.application = application; //通过监听器将这个application对象set进来,因为这里是无法拿application对象的
}
@Override
//和监听器在项目启动的时候数据初始化的逻辑一样
public void run() {
System.out.println("----run----");
List<List<Product>> bigList = new ArrayList<List<Product>>(); //bigList中存放一个装有Category类的list
// 1. 查询出热点类别
for(Category category : categoryService.queryByHot(true)) {
//根据热点类别id获取推荐商品信息
List<Product> lst = productService.querByCategoryId(category.getId());
bigList.add(lst); //将装有category的list放到bigList中
}
// 2. 把查询的bigList交给application内置对象
application.setAttribute("bigList", bigList); //假设我们已经拿到了application对象
}
}
//@Component //监听器是web层的组件,它是tomcat实例化的,不是Spring实例化的。不能放到Spring中
public class InitDataListener implements ServletContextListener {
private ProductTimerTask productTimerTask = null; //定义一个ProductTimerTask对象
private ApplicationContext context = null;
@Override
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent event) {
context = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
productTimerTask = (ProductTimerTask) context.getBean("productTimerTask");//从配置文件中获取ProductTimerTask对象
//把内置对象交给productTimerTask,因为productTimerTask里面是拿不到application的,只能通过监听器set给它
productTimerTask.setApplication(event.getServletContext());
//通过设置定时器,让首页的数据每个一小时同步一次(配置为守护线程)
new Timer(true).schedule(productTimerTask, 0, 1000*60*60);//每个一小时执行一次productTimerTask任务,即更新一下后台数据
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有