彻底理解spring的定制任务(scheduling)

本文介绍如何使用Spring框架配置定时任务,通过配置文件设置任务执行周期和延迟时间,简化任务调度流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

相信做软件的朋友都有这样的经历,我的软件是不是少了点什么东西呢?比如定时任务啊,

就拿新闻发布系统来说,如果新闻的数据更新太快,势必涉及一个问题,这些新闻不能由人工的去发布,应该让系统自己发布,这就需要用到定时定制任务了,以前定制任务无非就是设计一个Thread,并且设置运行时间片,让它到了那个时间执行一次,就ok了,让系统启动的时候启动它,想来也够简单的。不过有了 spring,我想这事情就更简单了。

看看spring的配置文件,想来就只有这个配置文件了

<bean id="infoCenterAutoBuildTask"
# class
="com.teesoo.teanet.scheduling.InfoCenterAutoBuildTask">
<property name="baseService" ref="baseService" />
<property name="htmlCreator" ref="htmlCreator" />
# bean>
#

<bean id="scheduledTask"
# class
="org.springframework.scheduling.timer.ScheduledTimerTask">
#

<property name="delay" value="10000" />
#

<property name="period" value="1000000" />
<property name="timerTask" ref="infoCenterAutoBuildTask" />
# bean>
#

#


<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
#

<ref bean="scheduledTask" />
# list>
# property>
# bean>

 

上面三个配置文件中只有一个配置文件是涉及到您自己的class的,其他的都是spring的类。很简单吧

我们只需要涉及一个class让他继承java.util.TimerTask;

 

   1.  BaseTask extends java.util.TimerTask {
   
2//用户只需要实现这个方面,把自己的任务放到这里
   3public void run(){
   
4. }

   
5. }

下面让我们来看看 spring的源代码

 

   1.  /*
   2. * Copyright 2002-2005 the original author or authors.
   3. *
   4. * Licensed under the Apache License, Version 2.0 (the "License");
   5. * you may not use this file except in compliance with the License.
   6. * You may obtain a copy of the License at
   7. *
   8. * 
http://www.apache.org/licenses/LICENSE-2.0
   9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. 
*/

  
16.

  
17package org.springframework.scheduling.timer;
  
18.

  
19import java.util.TimerTask;
  
20.

  
21/**
  22. * JavaBean that describes a scheduled TimerTask, consisting of
  23. * the TimerTask itself (or a Runnable to create a TimerTask for)
  24. * and a delay plus period. Period needs to be specified;
  25. * there is no point in a default for it.
  26. *
  27. *

      The JDK Timer does not offer more sophisticated scheduling
  28. * options such as cron expressions. Consider using Quartz for
  29. * such advanced needs.
  30. *
  31. *

      Note that Timer uses a TimerTask instance that is shared
  32. * between repeated executions, in contrast to Quartz which
  33. * instantiates a new Job for each execution.
  34. *
  35. * 
@author Juergen Hoeller
  36. * 
@since 19.02.2004
  37. * 
@see java.util.TimerTask
  38. * 
@see java.util.Timer#schedule(TimerTask, long, long)
  39. * 
@see java.util.Timer#scheduleAtFixedRate(TimerTask, long, long)
  40. 
*/

  
41public class ScheduledTimerTask {
  
42.

  
43private TimerTask timerTask;
  
44.

  
45private long delay = 0;
  
46.

  
47private long period = 0;
  
48.

  
49private boolean fixedRate = false;
  
50.

  
51.


  
52/**
  53. * Create a new ScheduledTimerTask,
  54. * to be populated via bean properties.
  55. * 
@see #setTimerTask
  56. * 
@see #setDelay
  57. * 
@see #setPeriod
  58. * 
@see #setFixedRate
  59. 
*/

  
60public ScheduledTimerTask() {
  
61. }

  
62.

  
63/**
  64. * Create a new ScheduledTimerTask, with default
  65. * one-time execution without delay.
  66. * 
@param timerTask the TimerTask to schedule
  67. 
*/

  
68public ScheduledTimerTask(TimerTask timerTask) {
  
69this.timerTask = timerTask;
  
70. }

  
71.

  
72/**
  73. * Create a new ScheduledTimerTask, with default
  74. * one-time execution with the given delay.
  75. * 
@param timerTask the TimerTask to schedule
  76. * 
@param delay the delay before starting the task for the first time (ms)
  77. 
*/

  
78public ScheduledTimerTask(TimerTask timerTask, long delay) {
  
79this.timerTask = timerTask;
  
80this.delay = delay;
  
81. }

  
82.

  
83/**
  84. * Create a new ScheduledTimerTask.
  85. * 
@param timerTask the TimerTask to schedule
  86. * 
@param delay the delay before starting the task for the first time (ms)
  87. * 
@param period the period between repeated task executions (ms)
  88. * 
@param fixedRate whether to schedule as fixed-rate execution
  89. 
*/

  
90public ScheduledTimerTask(TimerTask timerTask, long delay, long period, boolean fixedRate) {
  
91this.timerTask = timerTask;
  
92this.delay = delay;
  
93this.period = period;
  
94this.fixedRate = fixedRate;
  
95. }

  
96.

  
97/**
  98. * Create a new ScheduledTimerTask, with default
  99. * one-time execution without delay.
 100. * 
@param timerTask the Runnable to schedule as TimerTask
 101. 
*/

 
102public ScheduledTimerTask(Runnable timerTask) {
 
103. setRunnable(timerTask);
 
104. }

 
105.

 
106/**
 107. * Create a new ScheduledTimerTask, with default
 108. * one-time execution with the given delay.
 109. * 
@param timerTask the Runnable to schedule as TimerTask
 110. * 
@param delay the delay before starting the task for the first time (ms)
 111. 
*/

 
112public ScheduledTimerTask(Runnable timerTask, long delay) {
 
113. setRunnable(timerTask);
 
114this.delay = delay;
 
115. }

 
116.

 
117/**
 118. * Create a new ScheduledTimerTask.
 119. * 
@param timerTask the Runnable to schedule as TimerTask
 120. * 
@param delay the delay before starting the task for the first time (ms)
 121. * 
@param period the period between repeated task executions (ms)
 122. * 
@param fixedRate whether to schedule as fixed-rate execution
 123. 
*/

 
124public ScheduledTimerTask(Runnable timerTask, long delay, long period, boolean fixedRate) {
 
125. setRunnable(timerTask);
 
126this.delay = delay;
 
127this.period = period;
 
128this.fixedRate = fixedRate;
 
129. }

 
130.

 
131.


 
132/**
 133. * Set the Runnable to schedule as TimerTask.
 134. * 
@see DelegatingTimerTask
 135. 
*/

 
136public void setRunnable(Runnable timerTask) {
 
137this.timerTask = new DelegatingTimerTask(timerTask);
 
138. }

 
139.

 
140/**
 141. * Set the TimerTask to schedule.
 142. 
*/

 
143public void setTimerTask(TimerTask timerTask) {
 
144this.timerTask = timerTask;
 
145. }

 
146.

 
147/**
 148. * Return the TimerTask to schedule.
 149. 
*/

 
150public TimerTask getTimerTask() {
 
151return timerTask;
 
152. }

 
153.

 
154/**
 155. * Set the delay before starting the task for the first time,
 156. * in milliseconds. Default is 0, immediately starting the
 157. * task after successful scheduling.
 158. 
*/

 
159public void setDelay(long delay) {
 
160this.delay = delay;
 
161. }

 
162.

 
163/**
 164. * Return the delay before starting the job for the first time.
 165. 
*/

 
166public long getDelay() {
 
167return delay;
 
168. }

 
169.

 
170/**
 171. * Set the period between repeated task executions, in milliseconds.
 172. * Default is 0, leading to one-time execution. In case of a positive
 173. * value, the task will be executed repeatedly, with the given interval
 174. * inbetween executions.
 175. *

      Note that the semantics of the period vary between fixed-rate
 176. * and fixed-delay execution.
 177. * 
@see #setFixedRate
 178. 
*/

 
179public void setPeriod(long period) {
 
180this.period = period;
 
181. }

 
182.

 
183/**
 184. * Return the period between repeated task executions.
 185. 
*/

 
186public long getPeriod() {
 
187return period;
 
188. }

 
189.

 
190/**
 191. * Set whether to schedule as fixed-rate execution, rather than
 192. * fixed-delay execution. Default is "false", i.e. fixed delay.
 193. *

      See Timer javadoc for details on those execution modes.
 194. * 
@see java.util.Timer#schedule(TimerTask, long, long)
 195. * 
@see java.util.Timer#scheduleAtFixedRate(TimerTask, long, long)
 196. 
*/

 
197public void setFixedRate(boolean fixedRate) {
 
198this.fixedRate = fixedRate;
 
199. }

 
200.

 
201/**
 202. * Return whether to schedule as fixed-rate execution.
 203. 
*/

 
204public boolean isFixedRate() {
 
205return fixedRate;
 
206. }

 
207.

 
208. }

说实话这个类也没什么,只是简单的包装了我们的timertask,里面也就只有几个属性,一个是时间片,一个是任务等。

真正运行我们的任务的类是:

java 代码
#
#

package org.springframework.scheduling.timer;
#

import java.util.Timer;
#

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
#

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
#

/**
# * FactoryBean that sets up a JDK 1.3+ Timer and exposes it for bean references.
# *
# *

Allows for registration of ScheduledTimerTasks, automatically starting
# * the Timer on initialization and cancelling it on destruction of the context.
# * In scenarios that just require static registration of tasks at startup,
# * there is no need to access the Timer instance itself in application code.
# *
# *

Note that Timer uses a TimerTask instance that is shared between
# * repeated executions, in contrast to Quartz which instantiates a new
# * Job for each execution.
# *
# * 
@author Juergen Hoeller
# * 
@since 19.02.2004
# * 
@see ScheduledTimerTask
# * 
@see java.util.Timer
# * 
@see java.util.TimerTask
*/

public class TimerFactoryBean implements FactoryBean, InitializingBean, DisposableBean {
#

protected final Log logger = LogFactory.getLog(getClass());
#

private ScheduledTimerTask[] scheduledTimerTasks;
#

private boolean daemon = false;
#

private Timer timer;
#

#


/**
# * Register a list of ScheduledTimerTask objects with the Timer that
# * this FactoryBean creates. Depending on each SchedulerTimerTask's
# * settings, it will be registered via one of Timer's schedule methods.
# * 
@see java.util.Timer#schedule(java.util.TimerTask, long)
# * 
@see java.util.Timer#schedule(java.util.TimerTask, long, long)
# * 
@see java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, long, long)
*/

public void setScheduledTimerTasks(ScheduledTimerTask[] scheduledTimerTasks) {
this.scheduledTimerTasks = scheduledTimerTasks;
# }

#

/**
# * Set whether the timer should use a daemon thread,
# * just executing as long as the application itself is running.
# *

Default is "false": The timer will automatically get cancelled on
# * destruction of this FactoryBean. Hence, if the application shuts down,
# * tasks will by default finish their execution. Specify "true" for eager
# * shutdown of threads that execute tasks.
# * 
@see java.util.Timer#Timer(boolean)
*/

public void setDaemon(boolean daemon) {
this.daemon = daemon;
# }

#

#


public void afterPropertiesSet() {
# logger.info(
"Initializing Timer");
this.timer = createTimer(this.daemon);
#

// Register all ScheduledTimerTasks.
if (this.scheduledTimerTasks != null{
for (int i = 0; i < this.scheduledTimerTasks.length; i++{
# ScheduledTimerTask scheduledTask 
= this.scheduledTimerTasks[i];
if (scheduledTask.getPeriod() > 0{
// repeated task execution
if (scheduledTask.isFixedRate()) {
this.timer.scheduleAtFixedRate(
# scheduledTask.getTimerTask(), scheduledTask.getDelay(), scheduledTask.getPeriod());
# }

else {
this.timer.schedule(
# scheduledTask.getTimerTask(), scheduledTask.getDelay(), scheduledTask.getPeriod());
# }

# }

else {
// One-time task execution.
this.timer.schedule(scheduledTask.getTimerTask(), scheduledTask.getDelay());
# }

# }

# }

# }

#

/**
# * Create a new Timer instance. Called by afterPropertiesSet.
# * Can be overridden in subclasses to provide custom Timer subclasses.
# * 
@param daemon whether to create a Timer that runs as daemon thread
# * 
@return a new Timer instance
# * 
@see #afterPropertiesSet()
# * 
@see java.util.Timer#Timer(boolean)
*/

protected Timer createTimer(boolean daemon) {
return new Timer(daemon);
# }

#

#


public Object getObject() {
return this.timer;
# }

#

public Class getObjectType() {
return Timer.class;
# }

#

public boolean isSingleton() {
return true;
# }

#

#


/**
# * Cancel the Timer on bean factory shutdown, stopping all scheduled tasks.
# * 
@see java.util.Timer#cancel()
*/

public void destroy() {
# logger.info(
"Cancelling Timer");
this.timer.cancel();
# }

#

# }
 

这个类就是运行我们任务的类了,我们可以定制N个任务,只需要塞到这里就ok了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值