---
title: "spring 定时器配置实例"
author: "wengcang"
date: "2015-05-29T11:05:48Z"
tags: ["java定时器", "spring定时器", "定时器"]
categories: ["开源软件"]
slug: "spring"
draft: false
lastmod: "2015-06-01T17:30:23Z"
id: 2215178
url: "https://xiaoshifanyan.iteye.com/blog/2215178"
---

cto有如下需求：

 

        要求各team leader(每人负责网站的一个行业栏目)将各项目部的数据从后台管理查询汇总并使用excel整理以附件形式发送至cto(发送时间不限)，貌似数据量很大，自己统计要疯，于是乎，写定时器执行无疑是个好选择，那我的需求就很简单了，

 

        首先，由于是门户网站，数据量访问较大，所以只能选择深夜“悄悄地”。。。。。

    

         1、每天凌晨3点钟启动“数据提取”timer，其负责 ：

               1） 分类汇总数据；

               2） 持久化到数据库；

 

         2、每天凌晨4点钟启动“发送邮件”timer，主要用来将数据库里汇总好的相应数据提取并e-mail给cto

 

timer关键代码：

         我选择使用annotation方式，代码简单轻巧，

         1) 在spring配置文件的xmlns和xsi:schemaLocation声明处分别添加

           

```
task="http://www.springframework.org/schema/task"
和
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
```

       

          2) 开启task任务扫描注解

 

        

```
<task:annotation-driven/>
```

 

         3) 开启annotation,并配置扫描位置

 

```
<context:annotation-config />
<context:component-scan base-package="com.sina" />
```

 

         4) 接口：SpringTimerService

 

```
                /**
		 * spring 定时器接口
		 * @author Jar chang
		 */
		public interface SpringTimerService {
			/**
			 * 数据提取定时器
			 */
			public void runDataCollectionTimer();
			
			/**
			 * 发送邮件定时器
			 */
			public void runSendStatisticsEmailTimer();
			
		}
```

 

              5) service实现

 

    

```
                  @Component
		  public class SpringTimerServiceImpl implements SpringTimerService{
			
			@Resource
			private SpringTimerDao springTimerDaoImpl;
			
			@Override
			@Scheduled(cron="0 0 3 * * ?")
			//此处配置定时器具体的生效时间，关于cron表达式很简单：请百度
			public void runDataCollectionTimer() {
				springTimerDaoImpl.runCollection();
				//。。。。代码略
			}

			@Override
			@Scheduled(cron="0 0 4 * * ?")
			public void runSendStatisticsEmailTimer() {
				springTimerDaoImpl.runSendEmail();
				//。。。。代码略
			}
		}
```

 

 

              6) dao层是具体的从数据库取数据以及发送邮件的代码，网上一大堆，就不多做声明了#11

 

     需要注意的地方：

        1) 定时器任务方法不能有返回值

        2) spring的@Scheduled注解必须写在实现类上

        3) 定时任务不能启动请检查spring配置文件中的default-lazy-init="true",将其修改为false，因为默认懒

 

加载的情况定时器不会执行