---
title: "spring定时器启动两次原因及解决"
author: "linlargy"
date: "2013-04-14T00:17:06Z"
tags: ["Spring", "XML", "quartz"]
categories: ["行业应用"]
slug: "spring"
draft: false
lastmod: "2013-04-14T01:08:04Z"
id: 1846991
url: "https://linlargy.iteye.com/blog/1846991"
---

查出来的解决方案,现在作一总结: 引发原因:定时器被启动了两次,重启了两个定时器线程(spring中timer定时器;quartz定时器); 第一次：web容器启动的时候，读取applicationContext.xml文件时，会加载一次。 第二次：Spring本身会加载applicationContext.xml一次。 根源定时器配置与其它spring配置全部写在applicationContext.xml文件里. 遗留问题: web容器读取spring配置文件时是如何进行第一次加载定时器的? 解决方案: 1,通过程序设置标志变量方式改变,此种方式不建议,从根本上不能解决问题,不作介绍 2,将定时器配置从spring主配置文件中分离,进行分次加载定时功能只由web容器加载; 配置文件样例如下(spring用的是3.0,quartz用的是2.0): web.xml配置文件主要涉及部分 \[code="xml"] contextConfigLocation classpath:springConf/applicationContext.xml, classpath:springConf/timerQuartz-Context.xml, classpath:springConf/timertask-Context.xml org.springframework.web.context.ContextLoaderListener springDispacher springDispacher org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:springConf/applicationContext.xml 0 springDispacher \*.do \[/code] 主spring配置文件中说明applicationContext.xml:\[code="xml"] \[/code] 顺利也复习一下定时器如何配置: spring中timer定时器的配置方法timertask-Context.xml \[code="xml"] 2000 300000 \[/code] quartz定时器配置方法:timerQuartz-Context.xml \[code="xml"] 0/5 * * * * ? 0/5 * * * * ? \[/code] 项目源码 列出jar包附件图