ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 彻底理解spring的定制任务(scheduling) (转 )

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

原创 Linux操作系统 作者:it01 时间:2019-05-26 11:48:08 0 删除 编辑
彻底理解spring的定制任务(scheduling) (转)
相信做软件的朋友都有这样的经历,我的软件是不是少了点什么东西呢?比如定时任务啊,

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

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

xml 代码
  1. <bean id="infoCenterAutoBuildTask"
  2. class="com.teesoo.teanet.scheduling.InfoCenterAutoBuildTask">
  3. <property name="baseService" ref="baseService" />
  4. <property name="htmlCreator" ref="htmlCreator" />
  5. bean>
  6. <bean id="scheduledTask"
  7. class="org.springframework.scheduling.timer.ScheduledTimerTask">
  8. <!-- wait 10 seconds before starting repeated execution -->
  9. <property name="delay" value="10000" />
  10. <!-- run every 50 seconds -->
  11. <property name="period" value="1000000" />
  12. <property name="timerTask" ref="infoCenterAutoBuildTask" />
  13. bean>
  14. <bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
  15. <property name="scheduledTimerTasks">
  16. <list>
  17. <!-- see the example above -->
  18. <ref bean="scheduledTask" />
  19. list>
  20. property>
  21. bean>

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

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

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

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

java 代码
  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. package org.springframework.scheduling.timer;
  17. import java.util.TimerTask;
  18. /**
  19. * JavaBean that describes a scheduled TimerTask, consisting of
  20. * the TimerTask itself (or a Runnable to create a TimerTask for)
  21. * and a delay plus period. Period needs to be specified;
  22. * there is no point in a default for it.
  23. *
  24. *

    The JDK Timer does not offer more sophisticated scheduling

  25. * options such as cron expressions. Consider using Quartz for
  26. * such advanced needs.
  27. *
  28. *

    Note that Timer uses a TimerTask instance that is shared

  29. * between repeated executions, in contrast to Quartz which
  30. * instantiates a new Job for each execution.
  31. *
  32. * @author Juergen Hoeller
  33. * @since 19.02.2004
  34. * @see java.util.TimerTask
  35. * @see java.util.Timer#schedule(TimerTask, long, long)
  36. * @see java.util.Timer#scheduleAtFixedRate(TimerTask, long, long)
  37. */
  38. public class ScheduledTimerTask {
  39. private TimerTask timerTask;
  40. private long delay = 0;
  41. private long period = 0;
  42. private boolean fixedRate = false;
  43. /**
  44. * Create a new ScheduledTimerTask,
  45. * to be populated via bean properties.
  46. * @see #setTimerTask
  47. * @see #setDelay
  48. * @see #setPeriod
  49. * @see #setFixedRate
  50. */
  51. public ScheduledTimerTask() {
  52. }
  53. /**
  54. * Create a new ScheduledTimerTask, with default
  55. * one-time execution without delay.
  56. * @param timerTask the TimerTask to schedule
  57. */
  58. public ScheduledTimerTask(TimerTask timerTask) {
  59. this.timerTask = timerTask;
  60. }
  61. /**
  62. * Create a new ScheduledTimerTask, with default
  63. * one-time execution with the given delay.
  64. * @param timerTask the TimerTask to schedule
  65. * @param delay the delay before starting the task for the first time (ms)
  66. */
  67. public ScheduledTimerTask(TimerTask timerTask, long delay) {
  68. this.timerTask = timerTask;
  69. this.delay = delay;
  70. }
  71. /**
  72. * Create a new ScheduledTimerTask.
  73. * @param timerTask the TimerTask to schedule
  74. * @param delay the delay before starting the task for the first time (ms)
  75. * @param period the period between repeated task executions (ms)
  76. * @param fixedRate whether to schedule as fixed-rate execution
  77. */
  78. public ScheduledTimerTask(TimerTask timerTask, long delay, long period, boolean fixedRate) {
  79. this.timerTask = timerTask;
  80. this.delay = delay;
  81. this.period = period;
  82. this.fixedRate = fixedRate;
  83. }
  84. /**
  85. * Create a new ScheduledTimerTask, with default
  86. * one-time execution without delay.
  87. * @param timerTask the Runnable to schedule as TimerTask
  88. */
  89. public ScheduledTimerTask(Runnable timerTask) {
  90. setRunnable(timerTask);
  91. }
  92. /**
  93. * Create a new ScheduledTimerTask, with default
  94. * one-time execution with the given delay.
  95. * @param timerTask the Runnable to schedule as TimerTask
  96. * @param delay the delay before starting the task for the first time (ms)
  97. */
  98. public ScheduledTimerTask(Runnable timerTask, long delay) {
  99. setRunnable(timerTask);
  100. this.delay = delay;
  101. }
  102. /**
  103. * Create a new ScheduledTimerTask.
  104. * @param timerTask the Runnable to schedule as TimerTask
  105. * @param delay the delay before starting the task for the first time (ms)
  106. * @param period the period between repeated task executions (ms)
  107. * @param fixedRate whether to schedule as fixed-rate execution
  108. */
  109. public ScheduledTimerTask(Runnable timerTask, long delay, long period, boolean fixedRate) {
  110. setRunnable(timerTask);
  111. this.delay = delay;
  112. this.period = period;
  113. this.fixedRate = fixedRate;
  114. }
  115. /**
  116. * Set the Runnable to schedule as TimerTask.
  117. * @see DelegatingTimerTask
  118. */
  119. public void setRunnable(Runnable timerTask) {
  120. this.timerTask = new DelegatingTimerTask(timerTask);
  121. }
  122. /**
  123. * Set the TimerTask to schedule.
  124. */
  125. public void setTimerTask(TimerTask timerTask) {
  126. this.timerTask = timerTask;
  127. }
  128. /**
  129. * Return the TimerTask to schedule.
  130. */
  131. public TimerTask getTimerTask() {
  132. return timerTask;
  133. }
  134. /**
  135. * Set the delay before starting the task for the first time,
  136. * in milliseconds. Default is 0, immediately starting the
  137. * task after successful scheduling.
  138. */
  139. public void setDelay(long delay) {
  140. this.delay = delay;
  141. }
  142. /**
  143. * Return the delay before starting the job for the first time.
  144. */
  145. public long getDelay() {
  146. return delay;
  147. }
  148. /**
  149. * Set the period between repeated task executions, in milliseconds.
  150. * Default is 0, leading to one-time execution. In case of a positive
  151. * value, the task will be executed repeatedly, with the given interval
  152. * inbetween executions.
  153. *

    Note that the semantics of the period vary between fixed-rate

  154. * and fixed-delay execution.
  155. * @see #setFixedRate
  156. */
  157. public void setPeriod(long period) {
  158. this.period = period;
  159. }
  160. /**
  161. * Return the period between repeated task executions.
  162. */
  163. public long getPeriod() {
  164. return period;
  165. }
  166. /**
  167. * Set whether to schedule as fixed-rate execution, rather than
  168. * fixed-delay execution. Default is "false", i.e. fixed delay.
  169. *

    See Timer javadoc for details on those execution modes.

  170. * @see java.util.Timer#schedule(TimerTask, long, long)
  171. * @see java.util.Timer#scheduleAtFixedRate(TimerTask, long, long)
  172. */
  173. public void setFixedRate(boolean fixedRate) {
  174. this.fixedRate = fixedRate;
  175. }
  176. /**
  177. * Return whether to schedule as fixed-rate execution.
  178. */
  179. public boolean isFixedRate() {
  180. return fixedRate;
  181. }
  182. }

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

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

java 代码
  1. /*
  2. * Copyright 2002-2006 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. package org.springframework.scheduling.timer;
  17. import java.util.Timer;
  18. import org.apache.commons.logging.Log;
  19. import org.apache.commons.logging.LogFactory;
  20. import org.springframework.beans.factory.DisposableBean;
  21. import org.springframework.beans.factory.FactoryBean;
  22. import org.springframework.beans.factory.InitializingBean;
  23. /**
  24. * FactoryBean that sets up a JDK 1.3+ Timer and exposes it for bean references.
  25. *
  26. *

    Allows for registration of ScheduledTimerTasks, automatically starting

  27. * the Timer on initialization and cancelling it on destruction of the context.
  28. * In scenarios that just require static registration of tasks at startup,
  29. * there is no need to access the Timer instance itself in application code.
  30. *
  31. *

    Note that Timer uses a TimerTask instance that is shared between

  32. * repeated executions, in contrast to Quartz which instantiates a new
  33. * Job for each execution.
  34. *
  35. * @author Juergen Hoeller
  36. * @since 19.02.2004
  37. * @see ScheduledTimerTask
  38. * @see java.util.Timer
  39. * @see java.util.TimerTask
  40. */
  41. public class TimerFactoryBean implements FactoryBean, InitializingBean, DisposableBean {
  42. protected final Log logger = LogFactory.getLog(getClass());
  43. private ScheduledTimerTask[] scheduledTimerTasks;
  44. private boolean daemon = false;
  45. private Timer timer;
  46. /**
  47. * Register a list of ScheduledTimerTask objects with the Timer that
  48. * this FactoryBean creates. Depending on each SchedulerTimerTask's
  49. * settings, it will be registered via one of Timer's schedule methods.
  50. * @see java.util.Timer#schedule(java.util.TimerTask, long)
  51. * @see java.util.Timer#schedule(java.util.TimerTask, long, long)
  52. * @see java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, long, long)
  53. */
  54. public void setScheduledTimerTasks(ScheduledTimerTask[] scheduledTimerTasks) {
  55. this.scheduledTimerTasks = scheduledTimerTasks;
  56. }
  57. /**
  58. * Set whether the timer should use a daemon thread,
  59. * just executing as long as the application itself is running.
  60. *

    Default is "false": The timer will automatically get cancelled on

  61. * destruction of this FactoryBean. Hence, if the application shuts down,
  62. * tasks will by default finish their execution. Specify "true" for eager
  63. * shutdown of threads that execute tasks.
  64. * @see java.util.Timer#Timer(boolean)
  65. */
  66. public void setDaemon(boolean daemon) {
  67. this.daemon = daemon;
  68. }
  69. public void afterPropertiesSet() {
  70. logger.info("Initializing Timer");
  71. this.timer = createTimer(this.daemon);
  72. // Register all ScheduledTimerTasks.
  73. if (this.scheduledTimerTasks != null) {
  74. for (int i = 0; i < this.scheduledTimerTasks.length; i++) {
  75. ScheduledTimerTask scheduledTask = this.scheduledTimerTasks[i];
  76. if (scheduledTask.getPeriod() > 0) {
  77. // repeated task execution
  78. if (scheduledTask.isFixedRate()) {
  79. this.timer.scheduleAtFixedRate(
  80. scheduledTask.getTimerTask(), scheduledTask.getDelay(), scheduledTask.getPeriod());
  81. }
  82. else {
  83. this.timer.schedule(
  84. scheduledTask.getTimerTask(), scheduledTask.getDelay(), scheduledTask.getPeriod());
  85. }
  86. }
  87. else {
  88. // One-time task execution.
  89. this.timer.schedule(scheduledTask.getTimerTask(), scheduledTask.getDelay());
  90. }
  91. }
  92. }
  93. }
  94. /**
  95. * Create a new Timer instance. Called by afterPropertiesSet.
  96. * Can be overridden in subclasses to provide custom Timer subclasses.
  97. * @param daemon whether to create a Timer that runs as daemon thread
  98. * @return a new Timer instance
  99. * @see #afterPropertiesSet()
  100. * @see java.util.Timer#Timer(boolean)
  101. */
  102. protected Timer createTimer(boolean daemon) {
  103. return new Timer(daemon);
  104. }
  105. public Object getObject() {
  106. return this.timer;
  107. }
  108. public Class getObjectType() {
  109. return Timer.class;
  110. }
  111. public boolean isSingleton() {
  112. return true;
  113. }
  114. /**
  115. * Cancel the Timer on bean factory shutdown, stopping all scheduled tasks.
  116. * @see java.util.Timer#cancel()
  117. */
  118. public void destroy() {
  119. logger.info("Cancelling Timer");
  120. this.timer.cancel();
  121. }
  122. }

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

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12467/viewspace-148295/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2002-05-25

  • 博文量
    411
  • 访问量
    304553