Class ThreadPoolTaskScheduler
- java.lang.Object
- org.springframework.util.CustomizableThreadCreator
- org.springframework.scheduling.concurrent.CustomizableThreadFactory
- org.springframework.scheduling.concurrent.ExecutorConfigurationSupport
- org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler
- All Implemented Interfaces:
Serializable,Executor,ThreadFactory,Aware,BeanNameAware,DisposableBean,InitializingBean,AsyncListenableTaskExecutor,AsyncTaskExecutor,TaskExecutor,SchedulingTaskExecutor,TaskScheduler
public class ThreadPoolTaskScheduler extends ExecutorConfigurationSupport implements AsyncListenableTaskExecutor, SchedulingTaskExecutor, TaskScheduler
Implementation of Spring'sTaskSchedulerinterface, wrapping a nativeScheduledThreadPoolExecutor.- Since:
- 3.0
- Author:
- Juergen Hoeller, Mark Fisher
- See Also:
setPoolSize(int),setRemoveOnCancelPolicy(boolean),ExecutorConfigurationSupport.setThreadFactory(java.util.concurrent.ThreadFactory),setErrorHandler(org.springframework.util.ErrorHandler), Serialized Form
Field Summary
Fields inherited from class org.springframework.scheduling.concurrent.ExecutorConfigurationSupport
logger
Fields inherited from interface org.springframework.core.task.AsyncTaskExecutor
TIMEOUT_IMMEDIATE, TIMEOUT_INDEFINITE
Constructor Summary
Constructors Constructor Description ThreadPoolTaskScheduler()
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description protected ScheduledExecutorServicecreateExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler)Create a newScheduledExecutorServiceinstance.voidexecute(Runnable task)Execute the giventask.voidexecute(Runnable task, long startTimeout)Execute the giventask.intgetActiveCount()Return the number of currently active threads.intgetPoolSize()Return the current pool size.ScheduledExecutorServicegetScheduledExecutor()Return the underlying ScheduledExecutorService for native access.ScheduledThreadPoolExecutorgetScheduledThreadPoolExecutor()Return the underlying ScheduledThreadPoolExecutor, if available.protected ExecutorServiceinitializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler)Create the targetExecutorServiceinstance.booleanisRemoveOnCancelPolicy()Return the current setting for the remove-on-cancel mode.booleanprefersShortLivedTasks()Does thisTaskExecutorprefer short-lived tasks over long-lived tasks?ScheduledFuture<?>schedule(Runnable task, Date startTime)Schedule the givenRunnable, invoking it at the specified execution time.ScheduledFuture<?>schedule(Runnable task, Trigger trigger)Schedule the givenRunnable, invoking it whenever the trigger indicates a next execution time.ScheduledFuture<?>scheduleAtFixedRate(Runnable task, long period)Schedule the givenRunnable, starting as soon as possible and invoking it with the given period.ScheduledFuture<?>scheduleAtFixedRate(Runnable task, Date startTime, long period)Schedule the givenRunnable, invoking it at the specified execution time and subsequently with the given period.ScheduledFuture<?>scheduleWithFixedDelay(Runnable task, long delay)Schedule the givenRunnable, starting as soon as possible and invoking it with the given delay between the completion of one execution and the start of the next.ScheduledFuture<?>scheduleWithFixedDelay(Runnable task, Date startTime, long delay)Schedule the givenRunnable, invoking it at the specified execution time and subsequently with the given delay between the completion of one execution and the start of the next.voidsetErrorHandler(ErrorHandler errorHandler)Set a customErrorHandlerstrategy.voidsetPoolSize(int poolSize)Set the ScheduledExecutorService's pool size.voidsetRemoveOnCancelPolicy(boolean removeOnCancelPolicy)Set the remove-on-cancel mode onScheduledThreadPoolExecutor(JDK 7+).Future<?>submit(Runnable task)Submit a Runnable task for execution, receiving a Future representing that task.<T> Future<T>submit(Callable<T> task)Submit a Callable task for execution, receiving a Future representing that task.ListenableFuture<?>submitListenable(Runnable task)Submit aRunnabletask for execution, receiving aListenableFuturerepresenting that task.<T> ListenableFuture<T>submitListenable(Callable<T> task)Submit aCallabletask for execution, receiving aListenableFuturerepresenting that task.Methods inherited from class org.springframework.scheduling.concurrent.ExecutorConfigurationSupport
afterPropertiesSet, destroy, initialize, setAwaitTerminationSeconds, setBeanName, setRejectedExecutionHandler, setThreadFactory, setThreadNamePrefix, setWaitForTasksToCompleteOnShutdown, shutdown
Methods inherited from class org.springframework.scheduling.concurrent.CustomizableThreadFactory
newThread
Methods inherited from class org.springframework.util.CustomizableThreadCreator
createThread, getDefaultThreadNamePrefix, getThreadGroup, getThreadNamePrefix, getThreadPriority, isDaemon, nextThreadName, setDaemon, setThreadGroup, setThreadGroupName, setThreadPriority
Constructor Detail
ThreadPoolTaskScheduler
public ThreadPoolTaskScheduler()
Method Detail
setPoolSize
public void setPoolSize(int poolSize)
Set the ScheduledExecutorService's pool size. Default is 1.This setting can be modified at runtime, for example through JMX.
setRemoveOnCancelPolicy
@UsesJava7 public void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy)
Set the remove-on-cancel mode onScheduledThreadPoolExecutor(JDK 7+).Default is
false. If set totrue, the target executor will be switched into remove-on-cancel mode (if possible, with a soft fallback otherwise).This setting can be modified at runtime, for example through JMX.
setErrorHandler
public void setErrorHandler(ErrorHandler errorHandler)
Set a customErrorHandlerstrategy.
initializeExecutor
@UsesJava7 protected ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler)
Description copied from class:ExecutorConfigurationSupportCreate the targetExecutorServiceinstance. Called byafterPropertiesSet.- Specified by:
initializeExecutorin classExecutorConfigurationSupport- Parameters:
threadFactory- the ThreadFactory to userejectedExecutionHandler- the RejectedExecutionHandler to use- Returns:
- a new ExecutorService instance
- See Also:
ExecutorConfigurationSupport.afterPropertiesSet()
createExecutor
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler)
Create a newScheduledExecutorServiceinstance.The default implementation creates a
ScheduledThreadPoolExecutor. Can be overridden in subclasses to provide customScheduledExecutorServiceinstances.- Parameters:
poolSize- the specified pool sizethreadFactory- the ThreadFactory to userejectedExecutionHandler- the RejectedExecutionHandler to use- Returns:
- a new ScheduledExecutorService instance
- See Also:
ExecutorConfigurationSupport.afterPropertiesSet(),ScheduledThreadPoolExecutor
getScheduledExecutor
public ScheduledExecutorService getScheduledExecutor() throws IllegalStateException
Return the underlying ScheduledExecutorService for native access.- Returns:
- the underlying ScheduledExecutorService (never
null) - Throws:
IllegalStateException- if the ThreadPoolTaskScheduler hasn't been initialized yet
getScheduledThreadPoolExecutor
public ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor() throws IllegalStateException
Return the underlying ScheduledThreadPoolExecutor, if available.- Returns:
- the underlying ScheduledExecutorService (never
null) - Throws:
IllegalStateException- if the ThreadPoolTaskScheduler hasn't been initialized yet or if the underlying ScheduledExecutorService isn't a ScheduledThreadPoolExecutor- See Also:
getScheduledExecutor()
getPoolSize
public int getPoolSize()
Return the current pool size.Requires an underlying
ScheduledThreadPoolExecutor.
isRemoveOnCancelPolicy
@UsesJava7 public boolean isRemoveOnCancelPolicy()
Return the current setting for the remove-on-cancel mode.Requires an underlying
ScheduledThreadPoolExecutor.
getActiveCount
public int getActiveCount()
Return the number of currently active threads.Requires an underlying
ScheduledThreadPoolExecutor.
execute
public void execute(Runnable task)
Description copied from interface:TaskExecutorExecute the giventask.The call might return immediately if the implementation uses an asynchronous execution strategy, or might block in the case of synchronous execution.
- Specified by:
executein interfaceExecutor- Specified by:
executein interfaceTaskExecutor- Parameters:
task- theRunnableto execute (nevernull)
execute
public void execute(Runnable task, long startTimeout)
Description copied from interface:AsyncTaskExecutorExecute the giventask.- Specified by:
executein interfaceAsyncTaskExecutor- Parameters:
task- theRunnableto execute (nevernull)startTimeout- the time duration (milliseconds) within which the task is supposed to start. This is intended as a hint to the executor, allowing for preferred handling of immediate tasks. Typical values areAsyncTaskExecutor.TIMEOUT_IMMEDIATEorAsyncTaskExecutor.TIMEOUT_INDEFINITE(the default as used byTaskExecutor.execute(Runnable)).
submit
public Future<?> submit(Runnable task)
Description copied from interface:AsyncTaskExecutorSubmit a Runnable task for execution, receiving a Future representing that task. The Future will return anullresult upon completion.- Specified by:
submitin interfaceAsyncTaskExecutor- Parameters:
task- theRunnableto execute (nevernull)- Returns:
- a Future representing pending completion of the task
submit
public <T> Future<T> submit(Callable<T> task)
Description copied from interface:AsyncTaskExecutorSubmit a Callable task for execution, receiving a Future representing that task. The Future will return the Callable's result upon completion.- Specified by:
submitin interfaceAsyncTaskExecutor- Parameters:
task- theCallableto execute (nevernull)- Returns:
- a Future representing pending completion of the task
submitListenable
public ListenableFuture<?> submitListenable(Runnable task)
Description copied from interface:AsyncListenableTaskExecutorSubmit aRunnabletask for execution, receiving aListenableFuturerepresenting that task. The Future will return anullresult upon completion.- Specified by:
submitListenablein interfaceAsyncListenableTaskExecutor- Parameters:
task- theRunnableto execute (nevernull)- Returns:
- a
ListenableFuturerepresenting pending completion of the task
submitListenable
public <T> ListenableFuture<T> submitListenable(Callable<T> task)
Description copied from interface:AsyncListenableTaskExecutorSubmit aCallabletask for execution, receiving aListenableFuturerepresenting that task. The Future will return the Callable's result upon completion.- Specified by:
submitListenablein interfaceAsyncListenableTaskExecutor- Parameters:
task- theCallableto execute (nevernull)- Returns:
- a
ListenableFuturerepresenting pending completion of the task
prefersShortLivedTasks
public boolean prefersShortLivedTasks()
Description copied from interface:SchedulingTaskExecutorDoes thisTaskExecutorprefer short-lived tasks over long-lived tasks?A
SchedulingTaskExecutorimplementation can indicate whether it prefers submitted tasks to perform as little work as they can within a single task execution. For example, submitted tasks might break a repeated loop into individual subtasks which submit a follow-up task afterwards (if feasible).This should be considered a hint. Of course
TaskExecutorclients are free to ignore this flag and hence theSchedulingTaskExecutorinterface overall. However, thread pools will usually indicated a preference for short-lived tasks, to be able to perform more fine-grained scheduling.- Specified by:
prefersShortLivedTasksin interfaceSchedulingTaskExecutor- Returns:
trueif thisTaskExecutorprefers short-lived tasks
schedule
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger)
Description copied from interface:TaskSchedulerSchedule the givenRunnable, invoking it whenever the trigger indicates a next execution time.Execution will end once the scheduler shuts down or the returned
ScheduledFuturegets cancelled.- Specified by:
schedulein interfaceTaskScheduler- Parameters:
task- the Runnable to execute whenever the trigger firestrigger- an implementation of theTriggerinterface, e.g. aCronTriggerobject wrapping a cron expression- Returns:
- a
ScheduledFuturerepresenting pending completion of the task, ornullif the given Trigger object never fires (i.e. returnsnullfromTrigger.nextExecutionTime(org.springframework.scheduling.TriggerContext)) - See Also:
CronTrigger
schedule
public ScheduledFuture<?> schedule(Runnable task, Date startTime)
Description copied from interface:TaskSchedulerSchedule the givenRunnable, invoking it at the specified execution time.Execution will end once the scheduler shuts down or the returned
ScheduledFuturegets cancelled.- Specified by:
schedulein interfaceTaskScheduler- Parameters:
task- the Runnable to execute whenever the trigger firesstartTime- the desired execution time for the task (if this is in the past, the task will be executed immediately, i.e. as soon as possible)- Returns:
- a
ScheduledFuturerepresenting pending completion of the task
scheduleAtFixedRate
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period)
Description copied from interface:TaskSchedulerSchedule the givenRunnable, invoking it at the specified execution time and subsequently with the given period.Execution will end once the scheduler shuts down or the returned
ScheduledFuturegets cancelled.- Specified by:
scheduleAtFixedRatein interfaceTaskScheduler- Parameters:
task- the Runnable to execute whenever the trigger firesstartTime- the desired first execution time for the task (if this is in the past, the task will be executed immediately, i.e. as soon as possible)period- the interval between successive executions of the task (in milliseconds)- Returns:
- a
ScheduledFuturerepresenting pending completion of the task
scheduleAtFixedRate
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period)
Description copied from interface:TaskSchedulerSchedule the givenRunnable, starting as soon as possible and invoking it with the given period.Execution will end once the scheduler shuts down or the returned
ScheduledFuturegets cancelled.- Specified by:
scheduleAtFixedRatein interfaceTaskScheduler- Parameters:
task- the Runnable to execute whenever the trigger firesperiod- the interval between successive executions of the task (in milliseconds)- Returns:
- a
ScheduledFuturerepresenting pending completion of the task
scheduleWithFixedDelay
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay)
Description copied from interface:TaskSchedulerSchedule the givenRunnable, invoking it at the specified execution time and subsequently with the given delay between the completion of one execution and the start of the next.Execution will end once the scheduler shuts down or the returned
ScheduledFuturegets cancelled.- Specified by:
scheduleWithFixedDelayin interfaceTaskScheduler- Parameters:
task- the Runnable to execute whenever the trigger firesstartTime- the desired first execution time for the task (if this is in the past, the task will be executed immediately, i.e. as soon as possible)delay- the delay between the completion of one execution and the start of the next (in milliseconds)- Returns:
- a
ScheduledFuturerepresenting pending completion of the task
scheduleWithFixedDelay
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay)
Description copied from interface:TaskSchedulerSchedule the givenRunnable, starting as soon as possible and invoking it with the given delay between the completion of one execution and the start of the next.Execution will end once the scheduler shuts down or the returned
ScheduledFuturegets cancelled.- Specified by:
scheduleWithFixedDelayin interfaceTaskScheduler- Parameters:
task- the Runnable to execute whenever the trigger firesdelay- the interval between successive executions of the task (in milliseconds)- Returns:
- a
ScheduledFuturerepresenting pending completion of the task