延迟任务:调度程序在Spring 3中首次执行

时间:2010-01-17 10:48:41

标签: java spring

我有一个使用Spring 3进行依赖注入的简单应用程序。我有一个供用户查看的JFrame和一些与后端服务器和本地数据库维护同步的后台任务。

这是我的申请背景的相关部分:

<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延迟执行计划任务,直到我选择的那一刻?

3 个答案:

答案 0 :(得分:8)

这似乎被排除在<task:scheduled> bean定义之外,这是我上周才注意到的。

但请记住,<task:...>定义只是快捷方式,您可以始终使用显式方法,通过使用嵌套ScheduledExecutorFactoryBean bean定义ScheduledExecutorTask。这为您提供了更精细的控制,包括initialDelay

答案 1 :(得分:5)

我遇到了同样的问题并回到了TimerTask,因为它位于http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html中的25.7.1点

<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>

我希望在Spring 3.1中将<task:scheduled>中的initialDelay属性,因为在Spring 3.0中TimerFactoryBean是不推荐使用的。 您可以投票支持此问题:jira.springframework.org/browse/SPR-7022

答案 2 :(得分:3)

这已经在 spring 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>