2010-01-17 51 views
13

我有一個使用Spring 3進行依賴注入的簡單應用程序。我有一個供用戶查看的JFrame和一些後臺任務,用於與後端服務器和本地數據庫維護進行同步。延遲任務:在Spring 3中首次執行調度程序

這是我的應用程序上下文的相關部分:

<task:scheduler id="scheduler" pool-size="1"/> 
<task:scheduled-tasks scheduler="scheduler"> 
    <task:scheduled ref="synchronizer" method="incrementalSync" fixed-delay="600000"/> 
    ... more tasks ... 
</task:scheduled-tasks> 

<bean id="mainFrame" class="nl.gdries.myapp.client.ui.MainFrame"> 
    ... properties and such ... 
</bean> 

當我開始這個ApplicationContext調度立即開始執行甚至在我的UI加載的後臺任務。由於第一項任務在開始時比較沉重,我希望它在開始執行之前等待UI完全加載和顯示。

有沒有人知道如何告訴Spring延遲執行計劃的任務,直到我選擇的時刻?

回答

8

這似乎已被排除在<task:scheduled> bean定義之外,這是我上週纔剛剛注意到的。

但請記住,<task:...>定義只是快捷方式,您可以始終使用顯式方法,通過定義ScheduledExecutorFactoryBean和嵌套的ScheduledExecutorTask bean。這給你更好的控制,包括initialDelay

5

我有同樣的問題,回來TimerTask的,因爲它是在25.7.1點http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html

<bean id="scheduledTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> 
    <!-- wait 25 seconds before starting repeated execution --> 
    <property name="delay" value="25000" /> 
    <!-- run every 50 seconds --> 
    <property name="period" value="50000" /> 
    <property name="timerTask" ref="task" /> 
</bean> 

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

我希望在春天3.1將在initialDelay屬性在<task:scheduled>,因爲在Spring 3.0 TimerFactoryBean對已棄用。 您可以投票針對此問題:jira.springframework.org/browse/SPR-7022

+0

是有可能有動態的cron paramete r爲每個任務?使用TimeFactoryBean? – 2012-08-29 20:42:37

3

這已經通過的方式引入春季3.2所以如果你使用3.2模式是可以再次使用 - 比如:

<?xml version="1.0"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd 
     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"> 

....

上面可以讓你做到這一點:

<task:scheduler id="scheduler" pool-size="1"/> 
<task:scheduled-tasks scheduler="scheduler"> 
    <task:scheduled ref="synchronizer" method="incrementalSync" fixed-delay="600000" initial-delay="initial delay needed for the app to start"/> 
    ... more tasks ... 
</task:scheduled-tasks>