Class ThreadPoolTaskScheduler
- All Implemented Interfaces:
- Serializable,- Executor,- ThreadFactory,- EventListener,- Aware,- BeanNameAware,- DisposableBean,- InitializingBean,- ApplicationContextAware,- ApplicationListener<ContextClosedEvent>,- Lifecycle,- Phased,- SmartLifecycle,- AsyncListenableTaskExecutor,- AsyncTaskExecutor,- TaskExecutor,- SchedulingTaskExecutor,- TaskScheduler
TaskScheduler interface, wrapping
 a native ScheduledThreadPoolExecutor and providing
 all applicable configuration options for it. The default number of scheduler
 threads is 1; a higher number can be configured through setPoolSize(int).
 This is Spring's traditional scheduler variant, staying as close as possible to
 ScheduledExecutorService semantics. Task execution happens
 on the scheduler thread(s) rather than on separate execution threads. As a consequence,
 a ScheduledFuture handle (for example, from schedule(Runnable, Instant))
 represents the actual completion of the provided task (or series of repeated tasks).
- Since:
- 3.0
- Author:
- Juergen Hoeller, Mark Fisher
- See Also:
- 
- setPoolSize(int)
- setRemoveOnCancelPolicy(boolean)
- setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean)
- setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean)
- ExecutorConfigurationSupport.setThreadFactory(java.util.concurrent.ThreadFactory)
- setErrorHandler(org.springframework.util.ErrorHandler)
- ThreadPoolTaskExecutor
- SimpleAsyncTaskScheduler
- Serialized Form
 
- 
Field SummaryFields inherited from class org.springframework.scheduling.concurrent.ExecutorConfigurationSupportDEFAULT_PHASE, loggerFields inherited from interface org.springframework.core.task.AsyncTaskExecutorTIMEOUT_IMMEDIATE, TIMEOUT_INDEFINITE
- 
Constructor SummaryConstructors
- 
Method SummaryModifier and TypeMethodDescriptionprotected voidcancelRemainingTask(Runnable task) Cancel the given remaining task which never commenced execution, as returned fromExecutorService.shutdownNow().protected ScheduledExecutorServicecreateExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) Create a newScheduledExecutorServiceinstance.voidExecute the giventask.intReturn the number of currently active threads.getClock()Return the clock to use for scheduling purposes.intReturn the current pool size.Return the underlying ScheduledExecutorService for native access.Return the underlying ScheduledThreadPoolExecutor, if available.protected ExecutorServiceinitializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) Create the targetExecutorServiceinstance.booleanDeprecated.Schedule the givenRunnable, invoking it at the specified execution time.Schedule the givenRunnable, invoking it whenever the trigger indicates a next execution time.scheduleAtFixedRate(Runnable task, Duration period) Schedule the givenRunnable, starting as soon as possible and invoking it with the given period.scheduleAtFixedRate(Runnable task, Instant startTime, Duration period) Schedule the givenRunnable, invoking it at the specified execution time and subsequently with the given period.scheduleWithFixedDelay(Runnable task, Duration 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.scheduleWithFixedDelay(Runnable task, Instant startTime, Duration 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.voidSet the clock to use for scheduling purposes.voidsetContinueExistingPeriodicTasksAfterShutdownPolicy(boolean flag) Set whether to continue existing periodic tasks even when this executor has been shutdown.voidsetErrorHandler(ErrorHandler errorHandler) Set a customErrorHandlerstrategy.voidsetExecuteExistingDelayedTasksAfterShutdownPolicy(boolean flag) Set whether to execute existing delayed tasks even when this executor has been shutdown.voidsetPoolSize(int poolSize) Set the ScheduledExecutorService's pool size.voidsetRemoveOnCancelPolicy(boolean flag) Set the remove-on-cancel mode onScheduledThreadPoolExecutor.voidsetTaskDecorator(TaskDecorator taskDecorator) Specify a customTaskDecoratorto be applied to anyRunnableabout to be executed.Future<?>Submit a Runnable task for execution, receiving a Future representing that task.<T> Future<T>Submit a Callable task for execution, receiving a Future representing that task.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.ExecutorConfigurationSupportafterExecute, afterPropertiesSet, beforeExecute, destroy, getPhase, initialize, initiateEarlyShutdown, initiateShutdown, isRunning, onApplicationEvent, setAcceptTasksAfterContextClose, setApplicationContext, setAwaitTerminationMillis, setAwaitTerminationSeconds, setBeanName, setPhase, setRejectedExecutionHandler, setThreadFactory, setThreadNamePrefix, setVirtualThreads, setWaitForTasksToCompleteOnShutdown, shutdown, start, stop, stopMethods inherited from class org.springframework.scheduling.concurrent.CustomizableThreadFactorynewThreadMethods inherited from class org.springframework.util.CustomizableThreadCreatorcreateThread, getDefaultThreadNamePrefix, getThreadGroup, getThreadNamePrefix, getThreadPriority, isDaemon, nextThreadName, setDaemon, setThreadGroup, setThreadGroupName, setThreadPriorityMethods inherited from class java.lang.Objectclone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.springframework.context.ApplicationListenersupportsAsyncExecutionMethods inherited from interface org.springframework.core.task.AsyncTaskExecutorexecute, submitCompletable, submitCompletableMethods inherited from interface org.springframework.scheduling.SchedulingTaskExecutorprefersShortLivedTasksMethods inherited from interface org.springframework.context.SmartLifecycleisAutoStartupMethods inherited from interface org.springframework.scheduling.TaskSchedulerschedule, scheduleAtFixedRate, scheduleAtFixedRate, scheduleWithFixedDelay, scheduleWithFixedDelay
- 
Constructor Details- 
ThreadPoolTaskSchedulerpublic ThreadPoolTaskScheduler()
 
- 
- 
Method Details- 
setPoolSizepublic void setPoolSize(int poolSize) Set the ScheduledExecutorService's pool size. Default is 1.This setting can be modified at runtime, for example through JMX. 
- 
setRemoveOnCancelPolicypublic void setRemoveOnCancelPolicy(boolean flag) Set the remove-on-cancel mode onScheduledThreadPoolExecutor.Default is false. If set totrue, the target executor will be switched into remove-on-cancel mode (if possible).This setting can be modified at runtime, for example through JMX. 
- 
setContinueExistingPeriodicTasksAfterShutdownPolicypublic void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean flag) Set whether to continue existing periodic tasks even when this executor has been shutdown.Default is false. If set totrue, the target executor will be switched into continuing periodic tasks (if possible).This setting can be modified at runtime, for example through JMX. - Since:
- 5.3.9
- See Also:
 
- 
setExecuteExistingDelayedTasksAfterShutdownPolicypublic void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean flag) Set whether to execute existing delayed tasks even when this executor has been shutdown.Default is true. If set tofalse, the target executor will be switched into dropping remaining tasks (if possible).This setting can be modified at runtime, for example through JMX. - Since:
- 5.3.9
- See Also:
 
- 
setTaskDecoratorSpecify a customTaskDecoratorto be applied to anyRunnableabout to be executed.Note that such a decorator is not being applied to the user-supplied Runnable/Callablebut rather to the scheduled execution callback (a wrapper around the user-supplied task).The primary use case is to set some execution context around the task's invocation, or to provide some monitoring/statistics for task execution. - Since:
- 6.2
 
- 
setErrorHandlerSet a customErrorHandlerstrategy.
- 
setClockSet the clock to use for scheduling purposes.The default clock is the system clock for the default time zone. - Since:
- 5.3
- See Also:
 
- 
getClockDescription copied from interface:TaskSchedulerReturn the clock to use for scheduling purposes.- Specified by:
- getClockin interface- TaskScheduler
- See Also:
 
- 
initializeExecutorprotected ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) Description copied from class:ExecutorConfigurationSupportCreate the targetExecutorServiceinstance. Called byafterPropertiesSet.- Specified by:
- initializeExecutorin class- ExecutorConfigurationSupport
- Parameters:
- threadFactory- the ThreadFactory to use
- rejectedExecutionHandler- the RejectedExecutionHandler to use
- Returns:
- a new ExecutorService instance
- See Also:
 
- 
createExecutorprotected 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 size
- threadFactory- the ThreadFactory to use
- rejectedExecutionHandler- the RejectedExecutionHandler to use
- Returns:
- a new ScheduledExecutorService instance
- See Also:
 
- 
getScheduledExecutorReturn the underlying ScheduledExecutorService for native access.- Returns:
- the underlying ScheduledExecutorService (never null)
- Throws:
- IllegalStateException- if the ThreadPoolTaskScheduler hasn't been initialized yet
 
- 
getScheduledThreadPoolExecutorReturn 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:
 
- 
getPoolSizepublic int getPoolSize()Return the current pool size.Requires an underlying ScheduledThreadPoolExecutor.
- 
getActiveCountpublic int getActiveCount()Return the number of currently active threads.Requires an underlying ScheduledThreadPoolExecutor.
- 
isRemoveOnCancelPolicyDeprecated.as of 5.3.9, in favor of directgetScheduledThreadPoolExecutor()accessReturn the current setting for the remove-on-cancel mode.Requires an underlying ScheduledThreadPoolExecutor.
- 
executeDescription 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 interface- Executor
- Specified by:
- executein interface- TaskExecutor
- Parameters:
- task- the- Runnableto execute (never- null)
 
- 
submitDescription copied from interface:AsyncTaskExecutorSubmit a Runnable task for execution, receiving a Future representing that task. The Future will return anullresult upon completion.As of 6.1, this method comes with a default implementation that delegates to TaskExecutor.execute(Runnable).- Specified by:
- submitin interface- AsyncTaskExecutor
- Parameters:
- task- the- Runnableto execute (never- null)
- Returns:
- a Future representing pending completion of the task
 
- 
submitDescription 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.As of 6.1, this method comes with a default implementation that delegates to TaskExecutor.execute(Runnable).- Specified by:
- submitin interface- AsyncTaskExecutor
- Parameters:
- task- the- Callableto execute (never- null)
- Returns:
- a Future representing pending completion of the task
 
- 
submitListenableDescription copied from interface:AsyncListenableTaskExecutorSubmit aRunnabletask for execution, receiving aListenableFuturerepresenting that task. The Future will return anullresult upon completion.- Specified by:
- submitListenablein interface- AsyncListenableTaskExecutor
- Parameters:
- task- the- Runnableto execute (never- null)
- Returns:
- a ListenableFuturerepresenting pending completion of the task
 
- 
submitListenableDescription copied from interface:AsyncListenableTaskExecutorSubmit aCallabletask for execution, receiving aListenableFuturerepresenting that task. The Future will return the Callable's result upon completion.- Specified by:
- submitListenablein interface- AsyncListenableTaskExecutor
- Parameters:
- task- the- Callableto execute (never- null)
- Returns:
- a ListenableFuturerepresenting pending completion of the task
 
- 
cancelRemainingTaskDescription copied from class:ExecutorConfigurationSupportCancel the given remaining task which never commenced execution, as returned fromExecutorService.shutdownNow().- Overrides:
- cancelRemainingTaskin class- ExecutorConfigurationSupport
- Parameters:
- task- the task to cancel (typically a- RunnableFuture)
- See Also:
 
- 
scheduleDescription 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 interface- TaskScheduler
- Parameters:
- task- the Runnable to execute whenever the trigger fires
- trigger- an implementation of the- Triggerinterface, for example, a- CronTriggerobject wrapping a cron expression
- Returns:
- a ScheduledFuturerepresenting pending execution of the task, ornullif the given Trigger object never fires (i.e. returnsnullfromTrigger.nextExecution(org.springframework.scheduling.TriggerContext))
- See Also:
 
- 
scheduleDescription 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 interface- TaskScheduler
- Parameters:
- task- the Runnable to execute whenever the trigger fires
- startTime- 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 execution of the task
 
- 
scheduleAtFixedRateDescription 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 interface- TaskScheduler
- Parameters:
- task- the Runnable to execute whenever the trigger fires
- startTime- 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
- Returns:
- a ScheduledFuturerepresenting pending execution of the task
 
- 
scheduleAtFixedRateDescription 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 interface- TaskScheduler
- Parameters:
- task- the Runnable to execute whenever the trigger fires
- period- the interval between successive executions of the task
- Returns:
- a ScheduledFuturerepresenting pending execution of the task
 
- 
scheduleWithFixedDelayDescription 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 interface- TaskScheduler
- Parameters:
- task- the Runnable to execute whenever the trigger fires
- startTime- 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
- Returns:
- a ScheduledFuturerepresenting pending execution of the task
 
- 
scheduleWithFixedDelayDescription 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 interface- TaskScheduler
- Parameters:
- task- the Runnable to execute whenever the trigger fires
- delay- the delay between the completion of one execution and the start of the next
- Returns:
- a ScheduledFuturerepresenting pending execution of the task
 
 
- 
getScheduledThreadPoolExecutor()access