timer定时器在项目启动时执行了两次的原因及其解决办法

1 篇文章 0 订阅

time定时器在项目启动时执行了两次的原因及其解决办法

今天在项目的时候用到了java中的定时器计划任务。可以根据设置在特定的时间或间隔时间做特定的事。

下面给出一个例子:

        @Override
	public void afterPropertiesSet() throws Exception {
			
		Timer timer = new Timer();
		
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
			    System.out.println("定时器启动!");
			}
		};
		
		//定时器即时启动task,60分钟重新运行一次task
		timer.scheduleAtFixedRate(task, 0, 60*60*1000);
	}

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:web="http://java.sun.com/xml/ns/javaee"  
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
	id="sitms-rest" version="2.5">
	
	<display-name>sitms</display-name>
	<!-- 只做加载文件 -->
	<context-param>
	  <param-name>contextConfigLocation</param-name>
	  <param-value>classpath:spring/applicationContext-*.xml</param-value>
	</context-param>
	<context-param>
	  <param-name>log4jRefreshInterval</param-name>
	  <param-value>10000</param-value>
	</context-param>
	<context-param>
	  <param-name>log4jConfigLocation</param-name>
	  <param-value>classpath:log4j.properties</param-value>
	</context-param>
	<context-param>
	  <param-name>webAppRootKey</param-name>
	  <param-value>sitms-rest.root</param-value>
	</context-param>
	<listener>
	  <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	<listener>
	  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
	  <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>
	<filter>
	  <filter-name>CharacterEncodingFilter</filter-name>
	  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	  <init-param>
	    <param-name>encoding</param-name>
	    <param-value>utf-8</param-value>
	  </init-param>
	</filter>
	<filter-mapping>
	  <filter-name>CharacterEncodingFilter</filter-name>
	  <url-pattern>/*</url-pattern>
	</filter-mapping>
	<filter>
	  <filter-name>EncodingFilter</filter-name>
	  <filter-class>com.leaflink.sitms.filter.EncodingFilter</filter-class>
	</filter>
	<filter-mapping>
	  <filter-name>EncodingFilter</filter-name>
	  <url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- 启动文件 -->
	<servlet>
	  <servlet-name>sitms</servlet-name>
	  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	  <init-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>classpath:spring/springmvc.xml</param-value>
	  </init-param>
	  <load-on-startup>1</load-on-startup>
	</servlet>
	 <servlet-mapping>
	  <servlet-name>sitms</servlet-name>
	  <url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
</web-app>

配置的部分就是这样,然后我使用MyEclipse关联上Tomcat服务器。一切都是默认的设置,然后将本引用部署并启动Tomcat服务器。

这时候问题来了,我的任务类居然被创建了两次,下面是截取的部分日志数据:

2018-07-11 10:22:09,644 [localhost-startStop-1] DEBUG [org.mybatis.spring.mapper.ClassPathMapperScanner] - Creating MapperFactoryBean with name 'weChatLabelMapper' and 'com.leaflink.sitms.mapper.WeChatLabelMapper' mapperInterface
2018-07-11 10:22:09,863 [localhost-startStop-1] DEBUG [org.apache.ibatis.logging.LogFactory] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2018-07-11 10:22:10,479 [localhost-startStop-1] DEBUG [org.mybatis.spring.SqlSessionFactoryBean] - Parsed configuration file: 'class path resource [mybatis/SqlMapConfig.xml]'
2018-07-11 10:22:10,480 [localhost-startStop-1] DEBUG [org.mybatis.spring.SqlSessionFactoryBean] - Property 'mapperLocations' was not specified or no matching resources found
定时器启动!
2018-07-11 10:22:12,439 [localhost-startStop-1] INFO  [org.springframework.web.context.ContextLoader] - Root WebApplicationContext: initialization completed in 3968 ms
七月 11, 2018 10:22:12 上午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring FrameworkServlet 'sitms'
2018-07-11 10:22:12,505 [localhost-startStop-1] INFO  [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'sitms': initialization started
2018-07-11 10:22:12,508 [localhost-startStop-1] INFO  [org.springframework.web.context.support.XmlWebApplicationContext] - Refreshing WebApplicationContext for namespace 'sitms-servlet': startup date [Wed Jul 11 10:22:12 CST 2018]; parent: Root WebApplicationContext
定时器启动!

可以看到,执行了两次定时器,分别再ContextLoader和DispatcherServlet中实例化了,让我们再看一下配置文件:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>

该节点指派的applicationContext*.xml是用于实例化除servlet之外的所有对象的,可以说项目中绝大多数的service和dao层操作都由ContextLoaderListener传递给Spring来进行实例化。

<servlet>
    <servlet-name>sitms</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>sitms</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

这个是用来处理所有servlet的,没有它就无法通过请求地址来调用相应的Controller。

那么问题来了,有时候不注重对象初始化的分类,尤其是使用<context:component-scan base-package="com.**.**" />这样的包扫描形式统一初始化,很容易造成满足条件的对象被初始化两次,那么在计划任务的时候被执行两次也就不奇怪了。

所以不要将所有的初始化操作都放到一个配置文件中,更不要重复配置。不仅浪费资源,还很容易导致莫名其妙的故障。

解决方法:在配置文件中扫描包中指定扫描某个包,不要重复扫描

原先的applicationContext-dao.xml

<!--1 自动扫描 将标注Spring注解的类自动转化Bean 扫描了当前项目的所有包-->  
<context:component-scan base-package="com.***.***" />  

修改后:

<!--1 自动扫描 将标注Spring注解的类自动转化Bean 只扫描了service下的impl-->  
<context:component-scan base-package="com.***.***.service.impl" />  

原先的springmvc.xml

<!-- 扫描包加入 扫描了当前项目所有的包-->
<context:component-scan base-package="com.***.***" />

修改后:

<!-- 扫描包加入 指定扫描Controller-->
<context:component-scan base-package="com.***.***.controller" />
修改后运行结果:
2018-07-11 10:44:19,638 [localhost-startStop-1] DEBUG [org.mybatis.spring.mapper.ClassPathMapperScanner] - Creating MapperFactoryBean with name 'weChatLabelMapper' and 'com.leaflink.sitms.mapper.WeChatLabelMapper' mapperInterface
2018-07-11 10:44:19,881 [localhost-startStop-1] DEBUG [org.apache.ibatis.logging.LogFactory] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2018-07-11 10:44:20,650 [localhost-startStop-1] DEBUG [org.mybatis.spring.SqlSessionFactoryBean] - Parsed configuration file: 'class path resource [mybatis/SqlMapConfig.xml]'
2018-07-11 10:44:20,651 [localhost-startStop-1] DEBUG [org.mybatis.spring.SqlSessionFactoryBean] - Property 'mapperLocations' was not specified or no matching resources found
定时器启动!
2018-07-11 10:44:22,106 [localhost-startStop-1] INFO  [org.springframework.web.context.ContextLoader] - Root WebApplicationContext: initialization completed in 3298 ms
如果有什么不对的地方,欢迎指出!





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值