徹底理解spring的定製任務(scheduling)
相信做軟體的朋友都有這樣的經歷,我的軟體是不是少了點什麼東西呢?比如定時任務啊,
就拿新聞釋出系統來說,如果新聞的資料更新太快,勢必涉及一個問題,這些新聞不能由人工的去釋出,應該讓系統自己釋出,這就需要用到定時定製任務了,以前定製任務無非就是設計一個Thread,並且設定執行時間片,讓它到了那個時間執行一次,就ok了,讓系統啟動的時候啟動它,想來也夠簡單的。不過有了spring,我想這事情就更簡單了。
看看spring的配置檔案,想來就只有這個配置檔案了
xml 程式碼
- <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">
- <!-- wait 10 seconds before starting repeated execution -->
- <property name="delay" value="10000" />
- <!-- run every 50 seconds -->
- <property name="period" value="1000000" />
- <property name="timerTask" ref="infoCenterAutoBuildTask" />
- </bean>
- <bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
- <property name="scheduledTimerTasks">
- <list>
- <!-- see the example above -->
- <ref bean="scheduledTask" />
- </list>
- </property>
- </bean>
上面三個配置檔案中只有一個配置檔案是涉及到您自己的class的,其他的都是spring的類。很簡單吧
我們只需要涉及一個class讓他繼承java.util.TimerTask;
java 程式碼
- BaseTask extends java.util.TimerTask {
- //使用者只需要實現這個方面,把自己的任務放到這裡
- public void run(){
- }
- }
下面讓我們來看看 spring的原始碼
java 程式碼
- /*
- * Copyright 2002-2005 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- package org.springframework.scheduling.timer;
- import java.util.TimerTask;
- /**
- * JavaBean that describes a scheduled TimerTask, consisting of
- * the TimerTask itself (or a Runnable to create a TimerTask for)
- * and a delay plus period. Period needs to be specified;
- * there is no point in a default for it.
- *
- * <p>The JDK Timer does not offer more sophisticated scheduling
- * options such as cron expressions. Consider using Quartz for
- * such advanced needs.
- *
- * <p>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 java.util.TimerTask
- * @see java.util.Timer#schedule(TimerTask, long, long)
- * @see java.util.Timer#scheduleAtFixedRate(TimerTask, long, long)
- */
- public class ScheduledTimerTask {
- private TimerTask timerTask;
- private long delay = 0;
- private long period = 0;
- private boolean fixedRate = false;
- /**
- * Create a new ScheduledTimerTask,
- * to be populated via bean properties.
- * @see #setTimerTask
- * @see #setDelay
- * @see #setPeriod
- * @see #setFixedRate
- */
- public ScheduledTimerTask() {
- }
- /**
- * Create a new ScheduledTimerTask, with default
- * one-time execution without delay.
- * @param timerTask the TimerTask to schedule
- */
- public ScheduledTimerTask(TimerTask timerTask) {
- this.timerTask = timerTask;
- }
- /**
- * Create a new ScheduledTimerTask, with default
- * one-time execution with the given delay.
- * @param timerTask the TimerTask to schedule
- * @param delay the delay before starting the task for the first time (ms)
- */
- public ScheduledTimerTask(TimerTask timerTask, long delay) {
- this.timerTask = timerTask;
- this.delay = delay;
- }
- /**
- * Create a new ScheduledTimerTask.
- * @param timerTask the TimerTask to schedule
- * @param delay the delay before starting the task for the first time (ms)
- * @param period the period between repeated task executions (ms)
- * @param fixedRate whether to schedule as fixed-rate execution
- */
- public ScheduledTimerTask(TimerTask timerTask, long delay, long period, boolean fixedRate) {
- this.timerTask = timerTask;
- this.delay = delay;
- this.period = period;
- this.fixedRate = fixedRate;
- }
- /**
- * Create a new ScheduledTimerTask, with default
- * one-time execution without delay.
- * @param timerTask the Runnable to schedule as TimerTask
- */
- public ScheduledTimerTask(Runnable timerTask) {
- setRunnable(timerTask);
- }
- /**
- * Create a new ScheduledTimerTask, with default
- * one-time execution with the given delay.
- * @param timerTask the Runnable to schedule as TimerTask
- * @param delay the delay before starting the task for the first time (ms)
- */
- public ScheduledTimerTask(Runnable timerTask, long delay) {
- setRunnable(timerTask);
- this.delay = delay;
- }
- /**
- * Create a new ScheduledTimerTask.
- * @param timerTask the Runnable to schedule as TimerTask
- * @param delay the delay before starting the task for the first time (ms)
- * @param period the period between repeated task executions (ms)
- * @param fixedRate whether to schedule as fixed-rate execution
- */
- public ScheduledTimerTask(Runnable timerTask, long delay, long period, boolean fixedRate) {
- setRunnable(timerTask);
- this.delay = delay;
- this.period = period;
- this.fixedRate = fixedRate;
- }
- /**
- * Set the Runnable to schedule as TimerTask.
- * @see DelegatingTimerTask
- */
- public void setRunnable(Runnable timerTask) {
- this.timerTask = new DelegatingTimerTask(timerTask);
- }
- /**
- * Set the TimerTask to schedule.
- */
- public void setTimerTask(TimerTask timerTask) {
- this.timerTask = timerTask;
- }
- /**
- * Return the TimerTask to schedule.
- */
- public TimerTask getTimerTask() {
- return timerTask;
- }
- /**
- * Set the delay before starting the task for the first time,
- * in milliseconds. Default is 0, immediately starting the
- * task after successful scheduling.
- */
- public void setDelay(long delay) {
- this.delay = delay;
- }
- /**
- * Return the delay before starting the job for the first time.
- */
- public long getDelay() {
- return delay;
- }
- /**
- * Set the period between repeated task executions, in milliseconds.
- * Default is 0, leading to one-time execution. In case of a positive
- * value, the task will be executed repeatedly, with the given interval
- * inbetween executions.
- * <p>Note that the semantics of the period vary between fixed-rate
- * and fixed-delay execution.
- * @see #setFixedRate
- */
- public void setPeriod(long period) {
- this.period = period;
- }
- /**
- * Return the period between repeated task executions.
- */
- public long getPeriod() {
- return period;
- }
- /**
- * Set whether to schedule as fixed-rate execution, rather than
- * fixed-delay execution. Default is "false", i.e. fixed delay.
- * <p>See Timer javadoc for details on those execution modes.
- * @see java.util.Timer#schedule(TimerTask, long, long)
- * @see java.util.Timer#scheduleAtFixedRate(TimerTask, long, long)
- */
- public void setFixedRate(boolean fixedRate) {
- this.fixedRate = fixedRate;
- }
- /**
- * Return whether to schedule as fixed-rate execution.
- */
- public boolean isFixedRate() {
- return fixedRate;
- }
- }
說實話這個類也沒什麼,只是簡單的包裝了我們的timertask,裡面也就只有幾個屬性,一個是時間片,一個是任務等。
真正執行我們的任務的類是:
java 程式碼
- /*
- * Copyright 2002-2006 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- 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.
- *
- * <p>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.
- *
- * <p>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.
- * <p>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 <code>afterPropertiesSet</code>.
- * 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了。
相關文章
- 徹底理解synchronizedsynchronized
- 徹底理解JavaScript中的thisJavaScript
- 一文徹底理解微服務架構微服務架構
- Linux從頭學11:理解了這三個概念,才能徹底理解任務管理和任務切換Linux
- Spring 定時任務Spring
- 徹底理解Golang MapGolang
- 徹底理解正則
- 徹底理解ReentrantLockReentrantLock
- 徹底理解volatile
- 徹底理解Hive中的鎖Hive
- 徹底理解 JS 中 this 的指向JS
- 徹底理解js中this的指向JS
- 徹底理解Spring如何解決迴圈依賴Spring
- 12張圖帶你徹底理解分散式事務!!分散式
- Spring - Task定時任務Spring
- spring boot 定時任務Spring Boot
- 徹底理解cookie,session,tokenCookieSession
- spring boot中的定時任務Spring Boot
- 徹底理解js中的閉包JS
- 10 分鐘徹底理解 Redis 的持久化和主從複製Redis持久化
- 一文徹底理解Apache Hudi的多版本清理服務Apache
- spring定時任務註解Spring
- Spring Scheduler定時任務 + QuartzSpringquartz
- Spring Boot(九):定時任務Spring Boot
- spring定時任務相關Spring
- spring執行定時任務Spring
- Spring排程定時任務的方式Spring
- Spring定時任務的簡單例子Spring單例
- 徹底理解 Dart mixin 機制Dart
- 徹底理解kubernetes CNI
- 徹底理解連結器:四
- 小白(新手)如何徹底理解索引?索引
- (文摘)徹底理解webservice SOAP WSDLWeb
- 讓你徹底理解 “==”與 Equals
- 徹底理解Node.js中的BufferNode.js
- 徹底理解瀏覽器的跨域瀏覽器跨域
- JavaScript中this指標指向的徹底理解JavaScript指標
- Spring Boot 配置 Quartz 定時任務Spring Bootquartz