Class SimpleAsyncTaskScheduler
- All Implemented Interfaces:
- Serializable,- AutoCloseable,- Executor,- EventListener,- Aware,- ApplicationContextAware,- ApplicationListener<ContextClosedEvent>,- Lifecycle,- Phased,- SmartLifecycle,- AsyncListenableTaskExecutor,- AsyncTaskExecutor,- TaskExecutor,- TaskScheduler
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 SimpleAsyncTaskExecutor.setTaskTerminationTimeout(long),
 at the expense of task tracking overhead per execution thread at runtime.
 Supports limiting concurrent threads through SimpleAsyncTaskExecutor.setConcurrencyLimit(int).
 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 SimpleAsyncTaskExecutor.setVirtualThreads(boolean) to true.
 
Extends SimpleAsyncTaskExecutor and can serve as a fully capable
 replacement for it, e.g. as a single shared instance serving as a
 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(java.util.concurrent.Executor): 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.
- 
Field SummaryFields inherited from class org.springframework.core.task.SimpleAsyncTaskExecutorNO_CONCURRENCY, UNBOUNDED_CONCURRENCYFields inherited from interface org.springframework.core.task.AsyncTaskExecutorTIMEOUT_IMMEDIATE, TIMEOUT_INDEFINITEFields inherited from interface org.springframework.context.SmartLifecycleDEFAULT_PHASE
- 
Constructor SummaryConstructors
- 
Method SummaryModifier and TypeMethodDescriptionvoidclose()This close methods tracks the termination of active threads if a concretetask termination timeouthas been set.protected voidTemplate method for the actual execution of a task.getClock()Return the clock to use for scheduling purposes.intgetPhase()Return the lifecycle phase for pausing and resuming this executor.booleanCheck whether this component is currently running.voidHandle an application event.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.voidsetApplicationContext(ApplicationContext applicationContext) Set the ApplicationContext that this object runs in.voidSet the clock to use for scheduling purposes.voidsetPhase(int phase) Specify the lifecycle phase for pausing and resuming this executor.voidsetTargetTaskExecutor(Executor targetTaskExecutor) Specify a custom targetExecutorto delegate to for the individual execution of scheduled tasks.voidstart()Start this component.voidstop()Stop this component, typically in a synchronous fashion, such that the component is fully stopped upon return of this method.voidIndicates that a Lifecycle component must stop if it is currently running.Methods inherited from class org.springframework.core.task.SimpleAsyncTaskExecutorexecute, execute, getConcurrencyLimit, getThreadFactory, isActive, isThrottleActive, newThread, setConcurrencyLimit, setTaskDecorator, setTaskTerminationTimeout, setThreadFactory, setVirtualThreads, submit, submit, submitListenable, submitListenableMethods inherited from class org.springframework.util.CustomizableThreadCreatorcreateThread, getDefaultThreadNamePrefix, getThreadGroup, getThreadNamePrefix, getThreadPriority, isDaemon, nextThreadName, setDaemon, setThreadGroup, setThreadGroupName, setThreadNamePrefix, 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.AsyncTaskExecutorsubmitCompletable, submitCompletableMethods inherited from interface org.springframework.context.SmartLifecycleisAutoStartupMethods inherited from interface org.springframework.scheduling.TaskSchedulerschedule, scheduleAtFixedRate, scheduleAtFixedRate, scheduleWithFixedDelay, scheduleWithFixedDelay
- 
Constructor Details- 
SimpleAsyncTaskSchedulerpublic SimpleAsyncTaskScheduler()
 
- 
- 
Method Details- 
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:
 
- 
setPhasepublic void setPhase(int phase) Specify the lifecycle phase for pausing and resuming this executor. The default isSmartLifecycle.DEFAULT_PHASE.- See Also:
 
- 
getPhasepublic int getPhase()Return the lifecycle phase for pausing and resuming this executor.- Specified by:
- getPhasein interface- Phased
- Specified by:
- getPhasein interface- SmartLifecycle
- See Also:
 
- 
setTargetTaskExecutorSpecify a custom targetExecutorto 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 SimpleAsyncTaskExecutorarrangements kicks in with a new thread per task.
- 
setApplicationContextDescription copied from interface:ApplicationContextAwareSet 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 InitializingBean.afterPropertiesSet()or a custom init-method. Invoked afterResourceLoaderAware.setResourceLoader(org.springframework.core.io.ResourceLoader),ApplicationEventPublisherAware.setApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher)andMessageSourceAware, if applicable.- Specified by:
- setApplicationContextin interface- ApplicationContextAware
- Parameters:
- applicationContext- the ApplicationContext object to be used by this object
- See Also:
 
- 
doExecuteDescription copied from class:SimpleAsyncTaskExecutorTemplate method for the actual execution of a task.The default implementation creates a new Thread and starts it. - Overrides:
- doExecutein class- SimpleAsyncTaskExecutor
- Parameters:
- task- the Runnable to execute
- 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, e.g. a- CronTriggerobject 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:
 
- 
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 completion 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 completion 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 completion 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 completion 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 completion of the task
 
- 
startpublic void start()Description copied from interface:LifecycleStart 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. 
- 
stoppublic void stop()Description copied from interface:LifecycleStop this component, typically in a synchronous fashion, such that the component is fully stopped upon return of this method. Consider implementingSmartLifecycleand itsstop(Runnable)variant when asynchronous stop behavior is necessary.Note that this stop notification is not guaranteed to come before destruction: On regular shutdown, Lifecyclebeans 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. 
- 
stopDescription copied from interface:SmartLifecycleIndicates that a Lifecycle component must stop if it is currently running.The provided callback is used by the LifecycleProcessorto support an ordered, and potentially concurrent, shutdown of all components having a common shutdown order value. The callback must be executed after theSmartLifecyclecomponent does indeed stop.The LifecycleProcessorwill call only this variant of thestopmethod; i.e.Lifecycle.stop()will not be called forSmartLifecycleimplementations unless explicitly delegated to within the implementation of this method.The default implementation delegates to Lifecycle.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).- Specified by:
- stopin interface- SmartLifecycle
- See Also:
 
- 
isRunningpublic boolean isRunning()Description copied from interface:LifecycleCheck whether this component is currently running.In the case of a container, this will return trueonly if all components that apply are currently running.
- 
onApplicationEventDescription copied from interface:ApplicationListenerHandle an application event.- Specified by:
- onApplicationEventin interface- ApplicationListener<ContextClosedEvent>
- Parameters:
- event- the event to respond to
 
- 
closepublic void close()Description copied from class:SimpleAsyncTaskExecutorThis close methods tracks the termination of active threads if a concretetask termination timeouthas been set. Otherwise, it is not necessary to close this executor.- Specified by:
- closein interface- AutoCloseable
- Overrides:
- closein class- SimpleAsyncTaskExecutor
 
 
-