---
title: "Spring定时器的两种实现方式"
author: "chengtong_java"
date: "2015-04-17T15:18:40Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2015-04-17T15:18:40Z"
id: 2203304
url: "https://chengtong-java.iteye.com/blog/2203304"
---

Java代码  [![收藏代码](http://wenkaixuan.iteye.com/images/icon_star.png)]()

01. 有两种流行Spring定时器配置：Java的Timer类和OpenSymphony的Quartz。
02. 1.Java Timer定时
03. 首先继承java.util.TimerTask类实现run方法
04. package com.test;
05. import java.util.TimerTask;
06. public class CompanySampleTask extends TimerTask{
07. @Override
08. public void run() {
09. ...
10. }
11. }
12. 在Spring定义
13. 配置Spring定时器
14. &lt;bean id="scheduleReportTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"&gt;
15. &lt;property name="timerTask" ref="reportTimerTask" /&gt;
16. &lt;property name="period"&gt;
17. &lt;value&gt;86400000&lt;/value&gt;
18. &lt;/property&gt;
19. timerTask属性告诉ScheduledTimerTask运行哪个。86400000代表24个小时
20. 启动Spring定时器
21. Spring的TimerFactoryBean负责启动定时任务
22. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
23. &lt;beans xmlns="http://www.springframework.org/schema/beans"
24. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
25. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"&gt;
26. &lt;bean class="org.springframework.scheduling.timer.TimerFactoryBean"&gt;
27. &lt;property name="scheduledTimerTasks"&gt;
28. &lt;list&gt;&lt;ref bean="scheduleReportTask"/&gt;&lt;/list&gt;
29. &lt;/property&gt;
30. &lt;/bean&gt;
31. &lt;!-- scheduledTimerTasks里显示一个需要启动的定时器任务的列表。   可以通过设置delay属性延迟启动 --&gt;
32. &lt;bean id="scheduleReportTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"&gt;
33. &lt;property name="timerTask" ref="reportTimerTask" /&gt;
34. &lt;property name="period"&gt;   &lt;value&gt;30000&lt;/value&gt;   &lt;/property&gt;
35. &lt;property name="delay"&gt;   &lt;value&gt;60000&lt;/value&gt;   &lt;/property&gt;
36. &lt;/bean&gt;
37. &lt;bean id="reportTimerTask" class="com.test.CompanySampleTask"&gt;
38. &lt;property name="playService" ref="playService"&gt;&lt;/property&gt;
39. &lt;property name="advertiseService" ref="advertiseService"&gt;&lt;/property&gt;
40. &lt;/bean&gt;
41. &lt;/beans&gt;
42. 这个任务我们只能规定每隔24小时运行一次，无法精确到某时启动
43. 2.Quartz定时器
44. 首先继承QuartzJobBean类实现executeInternal方法
45. import org.quartz.JobExecutionContext;
46. import org.quartz.JobExecutionException;
47. import org.springframework.scheduling.quartz.QuartzJobBean;
48. public class EmailReportJob extends QuartzJobBean{
49. protected void executeInternal(JobExecutionContext arg0)
50. throws JobExecutionException {
51. ...
52. }
53. }
54. 在Spring中定义
55. &lt;bean id="reportJob" class="org.springframework.scheduling.quartz.JobDetailBean"&gt;
56. &lt;property name="jobClass"&gt;
57. &lt;value&gt;EmailReportJobvalue&gt;
58. property&gt;
59. &lt;property name="jobDataAsMap"&gt;
60. &lt;map&gt;
61. &lt;entry key="courseService"&gt;
62. &lt;ref bean="courseService"/&gt;
63. entry&gt;
64. map&gt;
65. property&gt;
66. bean&gt;
67. 在这里我们并没有直接声明一个EmailReportJob Bean，而是声明了一个JobDetailBean。这个是Quartz的特点。JobDetailBean是Quartz的org.quartz.JobDetail的子类，它要求通过jobClass属性来设置一个Job对象。
68. 使用Quartz的JobDetail中的另一个特别之处是EmailReportJob的courseService属性是间接设置的。JobDetail的jobDataAsMap属性接受一个Map，包括设置给jobClass的各种属性，当。JobDetailBean实例化时，它会将courseService Bean注入到EmailReportJob 的courseService 属性中。
69. 启动定时器
70. Quartz的org.quartz.Trigger类描述了何时及以怎样的频度运行一个Quartz工作。Spring提供了两个触发器SimpleTriggerBean和CronTriggerBean。
71. SimpleTriggerBean与scheduledTimerTasks类似。指定工作的执行频度，模仿scheduledTimerTasks配置 .
72. &lt;bean id="simpleReportTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"&gt;
73. &lt;property name="jobDetail" ref="reprotJob" /&gt;
74. &lt;property name="startDelay"&gt;
75. &lt;value&gt;360000value&gt;
76. property&gt;
77. &lt;property name="repeatInterval"&gt;
78. &lt;value&gt;86400000value&gt;
79. property&gt;
80. bean&gt;
81. startDelay也是延迟1个小时启动
82. CronTriggerBean指定工作的准确运行时间
83. &lt;bean id="cronReportTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"&gt;
84. &lt;property name="jobDetail" ref="reprotJob" /&gt;
85. &lt;property name="cronExpression"&gt;
86. &lt;value&gt;0 0 6 * * ?value&gt;
87. property&gt;
88. bean&gt;
89. 属性cronExpression告诉何时触发。最神秘就是cron表达式：
90. Linux系统的计划任务通常有cron来承担。一个cron表达式有至少6个（也可能7个）有空格分隔的时间元素。从左到右：
91. 1.秒2.分3.小时4.月份中的日期（1-31）5.月份（1-12或JAN-DEC)6.星期中的日期（1-7或SUN-SAT）7.年份（1970-2099）
92. 每个元素都显示的规定一个值（如6），一个区间（9-12），一个列表（9，11，13）或一个通配符（\*）。因为4和6这两个元素是互斥的，因此应该通过设置一个问号（？）来表明不想设置的那个字段，“/”如果值组合就表示重复次数（10/6表示每10秒重复6次）。
93. 启动定时器
94. &lt;bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"&gt;
95. &lt;property name="triggers"&gt;
96. &lt;list&gt;&lt;ref bean="cronReportTrigger"/&gt;list&gt;
97. property&gt;
98. bean&gt;
99. triggers属性接受一组触发器。