Package org.springframework.scheduling.concurrent

# 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`, `EventListener`, `org.springframework.beans.factory.Aware`, `org.springframework.beans.factory.BeanNameAware`, `org.springframework.beans.factory.DisposableBean`, `org.springframework.beans.factory.InitializingBean`, `ApplicationContextAware`, `ApplicationListener<ContextClosedEvent>`, `Lifecycle`, `Phased`, `SmartLifecycle`, `org.springframework.core.task.AsyncListenableTaskExecutor`, `org.springframework.core.task.AsyncTaskExecutor`, `org.springframework.core.task.TaskExecutor`, `SchedulingTaskExecutor`, `TaskScheduler`

public class ThreadPoolTaskScheduler extends ExecutorConfigurationSupport implements org.springframework.core.task.AsyncListenableTaskExecutor, SchedulingTaskExecutor, TaskScheduler
A standard implementation of Spring's `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 Summary

### Fields inherited from class org.springframework.scheduling.concurrent.ExecutorConfigurationSupport

`DEFAULT_PHASE, logger`

### Fields inherited from interface org.springframework.core.task.AsyncTaskExecutor

`TIMEOUT_IMMEDIATE, TIMEOUT_INDEFINITE`

## Constructor Summary

Constructors
Constructor
Description
`ThreadPoolTaskScheduler()`

## Method Summary

Modifier and Type
Method
Description
`protected void`
`cancelRemainingTask(Runnable task)`
Cancel the given remaining task which never commenced execution, as returned from `ExecutorService.shutdownNow()`.
`protected ScheduledExecutorService`
`createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler)`
Create a new `ScheduledExecutorService` instance.
`void`
`execute(Runnable task)`
`int`
`getActiveCount()`
Return the number of currently active threads.
`Clock`
`getClock()`
Return the clock to use for scheduling purposes.
`int`
`getPoolSize()`
Return the current pool size.
`ScheduledExecutorService`
`getScheduledExecutor()`
Return the underlying ScheduledExecutorService for native access.
`ScheduledThreadPoolExecutor`
`getScheduledThreadPoolExecutor()`
Return the underlying ScheduledThreadPoolExecutor, if available.
`protected ExecutorService`
`initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler)`
Create the target `ExecutorService` instance.
`boolean`
`isRemoveOnCancelPolicy()`
Deprecated.
as of 5.3.9, in favor of direct `getScheduledThreadPoolExecutor()` access
`ScheduledFuture<?>`
`schedule(Runnable task, Instant startTime)`
Schedule the given `Runnable`, invoking it at the specified execution time.
`ScheduledFuture<?>`
`schedule(Runnable task, Trigger trigger)`
Schedule the given `Runnable`, invoking it whenever the trigger indicates a next execution time.
`ScheduledFuture<?>`
`scheduleAtFixedRate(Runnable task, Duration period)`
Schedule the given `Runnable`, starting as soon as possible and invoking it with the given period.
`ScheduledFuture<?>`
`scheduleAtFixedRate(Runnable task, Instant startTime, Duration period)`
Schedule the given `Runnable`, invoking it at the specified execution time and subsequently with the given period.
`ScheduledFuture<?>`
`scheduleWithFixedDelay(Runnable task, Duration delay)`
Schedule the given `Runnable`, 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, Instant startTime, Duration delay)`
Schedule the given `Runnable`, 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.
`void`
`setClock(Clock clock)`
Set the clock to use for scheduling purposes.
`void`
`setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean flag)`
Set whether to continue existing periodic tasks even when this executor has been shutdown.
`void`
`setErrorHandler(org.springframework.util.ErrorHandler errorHandler)`
Set a custom `ErrorHandler` strategy.
`void`
`setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean flag)`
Set whether to execute existing delayed tasks even when this executor has been shutdown.
`void`
`setPoolSize(int poolSize)`
Set the ScheduledExecutorService's pool size.
`void`
`setRemoveOnCancelPolicy(boolean flag)`
Set the remove-on-cancel mode on `ScheduledThreadPoolExecutor`.
`void`
`setTaskDecorator(org.springframework.core.task.TaskDecorator taskDecorator)`
Specify a custom `TaskDecorator` to be applied to any `Runnable` about to be executed.
`Future<?>`
`submit(Runnable task)`
`<T> Future<T>`
`submit(Callable<T> task)`
`org.springframework.util.concurrent.ListenableFuture<?>`
`submitListenable(Runnable task)`
`<T> org.springframework.util.concurrent.ListenableFuture<T>`
`submitListenable(Callable<T> task)`

### Methods inherited from class org.springframework.scheduling.concurrent.ExecutorConfigurationSupport

`afterExecute, afterPropertiesSet, beforeExecute, destroy, getPhase, initialize, initiateEarlyShutdown, initiateShutdown, isRunning, onApplicationEvent, setAcceptTasksAfterContextClose, setApplicationContext, setAwaitTerminationMillis, setAwaitTerminationSeconds, setBeanName, setPhase, setRejectedExecutionHandler, setThreadFactory, setThreadNamePrefix, setVirtualThreads, setWaitForTasksToCompleteOnShutdown, shutdown, start, stop, stop`

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

### Methods inherited from class java.lang.Object

`clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

### Methods inherited from interface org.springframework.context.ApplicationListener

`supportsAsyncExecution`

### Methods inherited from interface org.springframework.core.task.AsyncTaskExecutor

`execute, submitCompletable, submitCompletable`

### Methods inherited from interface org.springframework.scheduling.SchedulingTaskExecutor

`prefersShortLivedTasks`

### Methods inherited from interface org.springframework.context.SmartLifecycle

`isAutoStartup`

### Methods inherited from interface org.springframework.scheduling.TaskScheduler

`schedule, scheduleAtFixedRate, scheduleAtFixedRate, scheduleWithFixedDelay, scheduleWithFixedDelay`

## Constructor Details

### ThreadPoolTaskScheduler

public ThreadPoolTaskScheduler()

## Method Details

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

public void setRemoveOnCancelPolicy(boolean flag)
Set the remove-on-cancel mode on `ScheduledThreadPoolExecutor`.

Default is `false`. If set to `true`, the target executor will be switched into remove-on-cancel mode (if possible).

This setting can be modified at runtime, for example through JMX.

See Also:
  - `ScheduledThreadPoolExecutor.setRemoveOnCancelPolicy(boolean)`

### setContinueExistingPeriodicTasksAfterShutdownPolicy

public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean flag)
Set whether to continue existing periodic tasks even when this executor has been shutdown.

Default is `false`. If set to `true`, 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:
  - `ScheduledThreadPoolExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean)`

### setExecuteExistingDelayedTasksAfterShutdownPolicy

public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean flag)
Set whether to execute existing delayed tasks even when this executor has been shutdown.

Default is `true`. If set to `false`, 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:
  - `ScheduledThreadPoolExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean)`

### setTaskDecorator

public void setTaskDecorator(org.springframework.core.task.TaskDecorator taskDecorator)
Specify a custom `TaskDecorator` to be applied to any `Runnable` about to be executed.

Note that such a decorator is not being applied to the user-supplied `Runnable`/`Callable` but 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

### setErrorHandler

public void setErrorHandler(org.springframework.util.ErrorHandler errorHandler)
Set a custom `ErrorHandler` strategy.

### setClock

public void setClock(Clock clock)
Set the clock to use for scheduling purposes.

The default clock is the system clock for the default time zone.

Since:
  5.3
See Also:
  - `Clock.systemDefaultZone()`

### getClock

public Clock getClock()
Description copied from interface: `TaskScheduler`
Return the clock to use for scheduling purposes.

Specified by:
  `getClock` in interface `TaskScheduler`
See Also:
  - `Clock.systemDefaultZone()`

### initializeExecutor

protected ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler)
Description copied from class: `ExecutorConfigurationSupport`
Create the target `ExecutorService` instance. Called by `afterPropertiesSet`.

Specified by:
  `initializeExecutor` in class `ExecutorConfigurationSupport`
Parameters:
  `threadFactory` - the ThreadFactory to use
  `rejectedExecutionHandler` - 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 new `ScheduledExecutorService` instance.

The default implementation creates a `ScheduledThreadPoolExecutor`. Can be overridden in subclasses to provide custom `ScheduledExecutorService` instances.

Parameters:
  `poolSize` - the specified pool size
  `threadFactory` - the ThreadFactory to use
  `rejectedExecutionHandler` - 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`.

See Also:
  - `getScheduledThreadPoolExecutor()`
  - `ThreadPoolExecutor.getPoolSize()`

### getActiveCount

public int getActiveCount()
Return the number of currently active threads.

Requires an underlying `ScheduledThreadPoolExecutor`.

See Also:
  - `getScheduledThreadPoolExecutor()`
  - `ThreadPoolExecutor.getActiveCount()`

### isRemoveOnCancelPolicy

@Deprecated public boolean isRemoveOnCancelPolicy()
Deprecated.
as of 5.3.9, in favor of direct `getScheduledThreadPoolExecutor()` access
Return the current setting for the remove-on-cancel mode.

Requires an underlying `ScheduledThreadPoolExecutor`.

### execute

public void execute(Runnable task)

Specified by:
  `execute` in interface `Executor`
Specified by:
  `execute` in interface `org.springframework.core.task.TaskExecutor`

### submit

public Future<?> submit(Runnable task)

Specified by:
  `submit` in interface `org.springframework.core.task.AsyncTaskExecutor`

### submit

public <T> Future<T> submit(Callable<T> task)

Specified by:
  `submit` in interface `org.springframework.core.task.AsyncTaskExecutor`

### submitListenable

public org.springframework.util.concurrent.ListenableFuture<?> submitListenable(Runnable task)

Specified by:
  `submitListenable` in interface `org.springframework.core.task.AsyncListenableTaskExecutor`

### submitListenable

public <T> org.springframework.util.concurrent.ListenableFuture<T> submitListenable(Callable<T> task)

Specified by:
  `submitListenable` in interface `org.springframework.core.task.AsyncListenableTaskExecutor`

### cancelRemainingTask

protected void cancelRemainingTask(Runnable task)
Description copied from class: `ExecutorConfigurationSupport`
Cancel the given remaining task which never commenced execution, as returned from `ExecutorService.shutdownNow()`.

Overrides:
  `cancelRemainingTask` in class `ExecutorConfigurationSupport`
Parameters:
  `task` - the task to cancel (typically a `RunnableFuture`)
See Also:
  - `ExecutorConfigurationSupport.shutdown()`
  - `Future.cancel(boolean)`

### schedule

@Nullable public ScheduledFuture<?> schedule(Runnable task, Trigger trigger)
Description copied from interface: `TaskScheduler`
Schedule the given `Runnable`, invoking it whenever the trigger indicates a next execution time.

Execution will end once the scheduler shuts down or the returned `ScheduledFuture` gets cancelled.

Specified by:
  `schedule` in interface `TaskScheduler`
Parameters:
  `task` - the Runnable to execute whenever the trigger fires
  `trigger` - an implementation of the `Trigger` interface, for example, a `CronTrigger` object wrapping a cron expression
Returns:
  a `ScheduledFuture` representing pending execution of the task, or `null` if the given Trigger object never fires (i.e. returns `null` from `Trigger.nextExecution(org.springframework.scheduling.TriggerContext)`)
See Also:
  - `CronTrigger`

### schedule

public ScheduledFuture<?> schedule(Runnable task, Instant startTime)
Description copied from interface: `TaskScheduler`
Schedule the given `Runnable`, invoking it at the specified execution time.

Execution will end once the scheduler shuts down or the returned `ScheduledFuture` gets cancelled.

Specified by:
  `schedule` in 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 `ScheduledFuture` representing pending execution of the task

### scheduleAtFixedRate

public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period)
Description copied from interface: `TaskScheduler`
Schedule the given `Runnable`, invoking it at the specified execution time and subsequently with the given period.

Execution will end once the scheduler shuts down or the returned `ScheduledFuture` gets cancelled.

Specified by:
  `scheduleAtFixedRate` in 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 `ScheduledFuture` representing pending execution of the task

### scheduleAtFixedRate

public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period)
Description copied from interface: `TaskScheduler`
Schedule the given `Runnable`, starting as soon as possible and invoking it with the given period.

Execution will end once the scheduler shuts down or the returned `ScheduledFuture` gets cancelled.

Specified by:
  `scheduleAtFixedRate` in interface `TaskScheduler`
Parameters:
  `task` - the Runnable to execute whenever the trigger fires
  `period` - the interval between successive executions of the task
Returns:
  a `ScheduledFuture` representing pending execution of the task

### scheduleWithFixedDelay

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime, Duration delay)
Description copied from interface: `TaskScheduler`
Schedule the given `Runnable`, 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 `ScheduledFuture` gets cancelled.

Specified by:
  `scheduleWithFixedDelay` in 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 `ScheduledFuture` representing pending execution of the task

### scheduleWithFixedDelay

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay)
Description copied from interface: `TaskScheduler`
Schedule the given `Runnable`, 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 `ScheduledFuture` gets cancelled.

Specified by:
  `scheduleWithFixedDelay` in 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 `ScheduledFuture` representing pending execution of the task