Top Description Fields Constructors Methods
org.springframework.scheduling.concurrent

public Class SimpleAsyncTaskScheduler

extends SimpleAsyncTaskExecutor
implements TaskScheduler, ApplicationContextAware, SmartLifecycle, ApplicationListener<ContextClosedEvent>
Class Inheritance
All Implemented Interfaces
org.springframework.context.ApplicationListener, java.util.EventListener, org.springframework.context.SmartLifecycle, org.springframework.context.Phased, org.springframework.context.Lifecycle, org.springframework.context.ApplicationContextAware, org.springframework.beans.factory.Aware, org.springframework.scheduling.TaskScheduler
Annotations
@SuppressWarnings:serial
Imports
java.time.Clock, .Duration, .Instant, java.util.concurrent.Executor, .Future, .RejectedExecutionException, .ScheduledExecutorService, .ScheduledFuture, .ScheduledThreadPoolExecutor, .TimeUnit, org.springframework.context.ApplicationContext, .ApplicationContextAware, .ApplicationListener, .SmartLifecycle, org.springframework.context.event.ContextClosedEvent, org.springframework.core.task.SimpleAsyncTaskExecutor, .TaskRejectedException, org.springframework.lang.Nullable, org.springframework.scheduling.TaskScheduler, .Trigger, org.springframework.scheduling.support.DelegatingErrorHandlingRunnable, .TaskUtils, org.springframework.util.ErrorHandler

References Deprecated

SimpleAsyncTaskExecutor is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

A simple implementation of Spring's TaskScheduler interface, using a single scheduler thread and executing every scheduled task in an individual separate thread. This is an attractive choice with virtual threads on JDK 21, expecting common usage with setVirtualThreads(true).

NOTE: Scheduling with a fixed delay enforces execution on the single scheduler thread, in order to provide traditional fixed-delay semantics! Prefer the use of fixed rates or cron triggers instead which are a better fit with this thread-per-task scheduler variant.

Supports a graceful shutdown through setTaskTerminationTimeout, at the expense of task tracking overhead per execution thread at runtime. Supports limiting concurrent threads through setConcurrencyLimit. By default, the number of concurrent task executions is unlimited. This allows for dynamic concurrency of scheduled task executions, in contrast to ThreadPoolTaskScheduler which requires a fixed pool size.

NOTE: This implementation does not reuse threads! Consider a thread-pooling TaskScheduler implementation instead, in particular for scheduling a large number of short-lived tasks. Alternatively, on JDK 21, consider setting setVirtualThreads to true.

Extends SimpleAsyncTaskExecutor and can serve as a fully capable replacement for it, e.g. as a single shared instance serving as a org.springframework.core.task.TaskExecutor as well as a TaskScheduler. This is generally not the case with other executor/scheduler implementations which tend to have specific constraints for the scheduler thread pool, requiring a separate thread pool for general executor purposes in practice.

As an alternative to the built-in thread-per-task capability, this scheduler can also be configured with a separate target executor for scheduled task execution through setTargetTaskExecutor: e.g. pointing to a shared ThreadPoolTaskExecutor bean. This is still rather different from a ThreadPoolTaskScheduler setup since it always uses a single scheduler thread while dynamically dispatching to the target thread pool which may have a dynamic core/max pool size range, participating in a shared concurrency limit.

Author
Juergen Hoeller
Since
6.1
See Also
setVirtualThreads, setTaskTerminationTimeout, setConcurrencyLimit, SimpleAsyncTaskExecutor, ThreadPoolTaskScheduler

Field Summary

Modifier and TypeField and Description
private ApplicationContext
private Clock
private final ExecutorLifecycleDelegate
private static final TimeUnit
private int
private final ScheduledExecutorService
private Executor
Inherited from org.springframework.core.task.SimpleAsyncTaskExecutor:
NO_CONCURRENCYUNBOUNDED_CONCURRENCY

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public void
close()

Overrides org.springframework.core.task.SimpleAsyncTaskExecutor.close.

Implements java.lang.AutoCloseable.close.

This close methods tracks the termination of active threads if a concrete task termination timeout has been set.

private ScheduledExecutorService
protected void
doExecute(Runnable
the Runnable to execute
task
)

Overrides org.springframework.core.task.SimpleAsyncTaskExecutor.doExecute.

Template method for the actual execution of a task.

public Clock
getClock()

Overrides default org.springframework.scheduling.TaskScheduler.getClock.

Return the clock to use for scheduling purposes.

public int
getPhase()

Overrides default org.springframework.context.SmartLifecycle.getPhase.

Return the lifecycle phase for pausing and resuming this executor.

public boolean
isRunning()

Implements org.springframework.context.Lifecycle.isRunning.

Check whether this component is currently running.

public void
onApplicationEvent(ContextClosedEvent
the event to respond to
event
)

Implements org.springframework.context.ApplicationListener.onApplicationEvent.

Handle an application event.

public ScheduledFuture<?>
schedule(Runnable
the Runnable to execute whenever the trigger fires
task
,
Trigger
an implementation of the Trigger interface, e.g. a org.springframework.scheduling.support.CronTrigger object wrapping a cron expression
trigger
)

Implements org.springframework.scheduling.TaskScheduler.schedule.

Schedule the given Runnable, invoking it whenever the trigger indicates a next execution time.

public ScheduledFuture<?>
schedule(Runnable
the Runnable to execute whenever the trigger fires
task
,
Instant
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)
startTime
)

Implements org.springframework.scheduling.TaskScheduler.schedule.

Schedule the given Runnable, invoking it at the specified execution time.

public ScheduledFuture<?>
scheduleAtFixedRate(Runnable
the Runnable to execute whenever the trigger fires
task
,
Instant
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)
startTime
,
Duration
the interval between successive executions of the task
period
)

Implements org.springframework.scheduling.TaskScheduler.scheduleAtFixedRate.

Schedule the given Runnable, invoking it at the specified execution time and subsequently with the given period.

public ScheduledFuture<?>
scheduleAtFixedRate(Runnable
the Runnable to execute whenever the trigger fires
task
,
Duration
the interval between successive executions of the task
period
)

Implements org.springframework.scheduling.TaskScheduler.scheduleAtFixedRate.

Schedule the given Runnable, starting as soon as possible and invoking it with the given period.

private Runnable
public ScheduledFuture<?>
scheduleWithFixedDelay(Runnable
the Runnable to execute whenever the trigger fires
task
,
Instant
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)
startTime
,
Duration
the delay between the completion of one execution and the start of the next
delay
)

Implements org.springframework.scheduling.TaskScheduler.scheduleWithFixedDelay.

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.

public ScheduledFuture<?>
scheduleWithFixedDelay(Runnable
the Runnable to execute whenever the trigger fires
task
,
Duration
the delay between the completion of one execution and the start of the next
delay
)

Implements org.springframework.scheduling.TaskScheduler.scheduleWithFixedDelay.

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.

public void
setApplicationContext(ApplicationContext
the ApplicationContext object to be used by this object
applicationContext
)

Implements org.springframework.context.ApplicationContextAware.setApplicationContext.

Set the ApplicationContext that this object runs in. Normally this call will be used to initialize the object.

public void
setClock(Clock clock)

Set the clock to use for scheduling purposes.

public void
setPhase(int phase)

Specify the lifecycle phase for pausing and resuming this executor.

public void
setTargetTaskExecutor(Executor targetTaskExecutor)

Specify a custom target Executor to delegate to for the individual execution of scheduled tasks.

public void
start()

Implements org.springframework.context.Lifecycle.start.

Start this component.

public void
stop()

Implements org.springframework.context.Lifecycle.stop.

Stop this component, typically in a synchronous fashion, such that the component is fully stopped upon return of this method.

public void
stop(Runnable callback)

Overrides default org.springframework.context.SmartLifecycle.stop.

Indicates that a Lifecycle component must stop if it is currently running.

private Runnable
Inherited from org.springframework.core.task.SimpleAsyncTaskExecutor:
executeexecutegetConcurrencyLimitgetThreadFactoryisActiveisThrottleActivenewThreadsetConcurrencyLimitsetTaskDecoratorsetTaskTerminationTimeoutsetThreadFactorysetVirtualThreadssubmitsubmitsubmitListenablesubmitListenable

Field Detail

applicationContextback to summary
private ApplicationContext applicationContext
Annotations
@Nullable
clockback to summary
private Clock clock
lifecycleDelegateback to summary
private final ExecutorLifecycleDelegate lifecycleDelegate
NANOback to summary
private static final TimeUnit NANO
phaseback to summary
private int phase
scheduledExecutorback to summary
private final ScheduledExecutorService scheduledExecutor
targetTaskExecutorback to summary
private Executor targetTaskExecutor
Annotations
@Nullable

Constructor Detail

SimpleAsyncTaskSchedulerback to summary
public SimpleAsyncTaskScheduler()

Method Detail

closeback to summary
public void close()

Overrides org.springframework.core.task.SimpleAsyncTaskExecutor.close.

Implements java.lang.AutoCloseable.close.

Doc from org.springframework.core.task.SimpleAsyncTaskExecutor.close.

This close methods tracks the termination of active threads if a concrete task termination timeout has been set. Otherwise, it is not necessary to close this executor.

Annotations
@Override
createScheduledExecutorback to summary
private ScheduledExecutorService createScheduledExecutor()
doExecuteback to summary
protected void doExecute(Runnable task)

Overrides org.springframework.core.task.SimpleAsyncTaskExecutor.doExecute.

Doc from org.springframework.core.task.SimpleAsyncTaskExecutor.doExecute.

Template method for the actual execution of a task.

The default implementation creates a new Thread and starts it.

Parameters
task:Runnable

the Runnable to execute

Annotations
@Override
getClockback to summary
public Clock getClock()

Overrides default org.springframework.scheduling.TaskScheduler.getClock.

Doc from org.springframework.scheduling.TaskScheduler.getClock.

Return the clock to use for scheduling purposes.

Annotations
@Override
getPhaseback to summary
public int getPhase()

Overrides default org.springframework.context.SmartLifecycle.getPhase.

Return the lifecycle phase for pausing and resuming this executor.

Annotations
@Override
See Also
setPhase
isRunningback to summary
public boolean isRunning()

Implements org.springframework.context.Lifecycle.isRunning.

Doc from org.springframework.context.Lifecycle.isRunning.

Check whether this component is currently running.

In the case of a container, this will return true only if all components that apply are currently running.

Returns:boolean

whether the component is currently running

Annotations
@Override
onApplicationEventback to summary
public void onApplicationEvent(ContextClosedEvent event)

Implements org.springframework.context.ApplicationListener.onApplicationEvent.

Doc from org.springframework.context.ApplicationListener.onApplicationEvent.

Handle an application event.

Parameters
event:ContextClosedEvent

the event to respond to

Annotations
@Override
scheduleback to summary
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger)

Implements org.springframework.scheduling.TaskScheduler.schedule.

Doc from org.springframework.scheduling.TaskScheduler.schedule.

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.

Parameters
task:Runnable

the Runnable to execute whenever the trigger fires

trigger:Trigger

an implementation of the Trigger interface, e.g. a org.springframework.scheduling.support.CronTrigger object wrapping a cron expression

Returns:ScheduledFuture<?>

a ScheduledFuture representing pending completion of the task, or null if the given Trigger object never fires (i.e. returns null from Trigger#nextExecution)

Annotations
@Override
@Nullable
scheduleback to summary
public ScheduledFuture<?> schedule(Runnable task, Instant startTime)

Implements org.springframework.scheduling.TaskScheduler.schedule.

Doc from org.springframework.scheduling.TaskScheduler.schedule.

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.

Parameters
task:Runnable

the Runnable to execute whenever the trigger fires

startTime:Instant

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:ScheduledFuture<?>

a ScheduledFuture representing pending completion of the task

Annotations
@Override
scheduleAtFixedRateback to summary
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period)

Implements org.springframework.scheduling.TaskScheduler.scheduleAtFixedRate.

Doc from org.springframework.scheduling.TaskScheduler.scheduleAtFixedRate.

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.

Parameters
task:Runnable

the Runnable to execute whenever the trigger fires

startTime:Instant

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

the interval between successive executions of the task

Returns:ScheduledFuture<?>

a ScheduledFuture representing pending completion of the task

Annotations
@Override
scheduleAtFixedRateback to summary
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period)

Implements org.springframework.scheduling.TaskScheduler.scheduleAtFixedRate.

Doc from org.springframework.scheduling.TaskScheduler.scheduleAtFixedRate.

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.

Parameters
task:Runnable

the Runnable to execute whenever the trigger fires

period:Duration

the interval between successive executions of the task

Returns:ScheduledFuture<?>

a ScheduledFuture representing pending completion of the task

Annotations
@Override
scheduledTaskback to summary
private Runnable scheduledTask(Runnable task)
scheduleWithFixedDelayback to summary
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime, Duration delay)

Implements org.springframework.scheduling.TaskScheduler.scheduleWithFixedDelay.

Doc from org.springframework.scheduling.TaskScheduler.scheduleWithFixedDelay.

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.

Parameters
task:Runnable

the Runnable to execute whenever the trigger fires

startTime:Instant

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

the delay between the completion of one execution and the start of the next

Returns:ScheduledFuture<?>

a ScheduledFuture representing pending completion of the task

Annotations
@Override
scheduleWithFixedDelayback to summary
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay)

Implements org.springframework.scheduling.TaskScheduler.scheduleWithFixedDelay.

Doc from org.springframework.scheduling.TaskScheduler.scheduleWithFixedDelay.

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.

Parameters
task:Runnable

the Runnable to execute whenever the trigger fires

delay:Duration

the delay between the completion of one execution and the start of the next

Returns:ScheduledFuture<?>

a ScheduledFuture representing pending completion of the task

Annotations
@Override
setApplicationContextback to summary
public void setApplicationContext(ApplicationContext applicationContext)

Implements org.springframework.context.ApplicationContextAware.setApplicationContext.

Doc from org.springframework.context.ApplicationContextAware.setApplicationContext.

Set the ApplicationContext that this object runs in. Normally this call will be used to initialize the object.

Invoked after population of normal bean properties but before an init callback such as org.springframework.beans.factory.InitializingBean#afterPropertiesSet() or a custom init-method. Invoked after ResourceLoaderAware#setResourceLoader, ApplicationEventPublisherAware#setApplicationEventPublisher and MessageSourceAware, if applicable.

Parameters
applicationContext:ApplicationContext

the ApplicationContext object to be used by this object

Annotations
@Override
setClockback to summary
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()
setPhaseback to summary
public void setPhase(int phase)

Specify the lifecycle phase for pausing and resuming this executor. The default is DEFAULT_PHASE.

See Also
SmartLifecycle#getPhase()
setTargetTaskExecutorback to summary
public void setTargetTaskExecutor(Executor targetTaskExecutor)

Specify a custom target Executor to delegate to for the individual execution of scheduled tasks. This can for example be set to a separate thread pool for executing scheduled tasks, whereas this scheduler keeps using its single scheduler thread.

If not set, the regular SimpleAsyncTaskExecutor arrangements kicks in with a new thread per task.

startback to summary
public void start()

Implements org.springframework.context.Lifecycle.start.

Doc from org.springframework.context.Lifecycle.start.

Start this component.

Should not throw an exception if the component is already running.

In the case of a container, this will propagate the start signal to all components that apply.

Annotations
@Override
stopback to summary
public void stop()

Implements org.springframework.context.Lifecycle.stop.

Doc from org.springframework.context.Lifecycle.stop.

Stop this component, typically in a synchronous fashion, such that the component is fully stopped upon return of this method. Consider implementing SmartLifecycle and its stop(Runnable) variant when asynchronous stop behavior is necessary.

Note that this stop notification is not guaranteed to come before destruction: On regular shutdown, Lifecycle beans will first receive a stop notification before the general destruction callbacks are being propagated; however, on hot refresh during a context's lifetime or on aborted refresh attempts, a given bean's destroy method will be called without any consideration of stop signals upfront.

Should not throw an exception if the component is not running (not started yet).

In the case of a container, this will propagate the stop signal to all components that apply.

Annotations
@Override
stopback to summary
public void stop(Runnable callback)

Overrides default org.springframework.context.SmartLifecycle.stop.

Doc from org.springframework.context.SmartLifecycle.stop.

Indicates that a Lifecycle component must stop if it is currently running.

The provided callback is used by the LifecycleProcessor to support an ordered, and potentially concurrent, shutdown of all components having a common shutdown order value. The callback must be executed after the SmartLifecycle component does indeed stop.

The LifecycleProcessor will call only this variant of the stop method; i.e. Lifecycle#stop() will not be called for SmartLifecycle implementations unless explicitly delegated to within the implementation of this method.

The default implementation delegates to stop() and immediately triggers the given callback in the calling thread. Note that there is no synchronization between the two, so custom implementations may at least want to put the same steps within their common lifecycle monitor (if any).

Annotations
@Override
taskOnSchedulerThreadback to summary
private Runnable taskOnSchedulerThread(Runnable task)