2015-02-11 107 views
5

我需要創建一個包含10個線程的任務調度程序,我們需要同時觸發並且每個線程將返回狀態爲完成或失敗的狀態。根據線程的結果,我們將調用db並從db獲取數據。該應用程序已經使用Spring Framework進行了配置。我明白,春天提供任務調度,但不知道如何使用它,春天新手需要幫助。那麼java的ScheduledExecutorService,我們可以使用它嗎?我們會得到一個優勢的優勢是什麼? Spring任務調度器和Java的ScheduledExecutorService有更好的選擇嗎?Spring Task Scheduler與Java的ScheduledExecutorService

回答

1

春季TaskExecutor實際上與java Executor接口相同。在Spring 2.0之後,TaskExecutor被引入來爲Java的Executor添加抽象,以便它隱藏Java SE不同版本和EE環境之間的實現細節。

由於您已經有了Spring環境,我強烈建議您使用spring schedulers。稍後如果有需要的話,你可以給其他Spring組件一個抽象的線程池等。

此外,還有一些預先構建的TaskExecutor實現,這是理想的,因爲你不必關心細節和你自己的實現。

1

最簡單的方法是在彈簧配置中使用提供的任務標籤。 注意以下

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:mvc="http://www.springframework.org/schema/mvc" 
     xmlns:ctx="http://www.springframework.org/schema/context" 
     xmlns:task="http://www.springframework.org/schema/task" 
     xmlns:util="http://www.springframework.org/schema/util" 
     xsi:schemaLocation=" 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd 
"> 

的「任務」命名空間,一旦你這樣做,你可以使用

<task:scheduler id="taskScheduler" pool-size="4"/> 
<task:scheduled-tasks scheduler="taskScheduler"> 
    <task:scheduled ref="someBean" method="someMethod" fixed-rate="21600000" initial-delay="60000"/> 
</task:scheduled-tasks> 

等 實際的計劃任務是與它的方法被調用的bean。你可以安排它在一個固定的延時或一個cron等

,您還可以在配置這樣的聲明執行人:

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> 
     <description>A task pool for general use</description> 
     <property name="corePoolSize" value="150" /> 
     <property name="maxPoolSize" value="200" /> 
     <property name="queueCapacity" value="10" /> 
     <property name="keepAliveSeconds" value="0"/> 
     <property name="waitForTasksToCompleteOnShutdown" value="false"/> 
    </bean> 

您可以使用執行人執行的併發任務池(注把這個bean放到你的bean中,看看它提供了什麼)。