@Scheduled annotation marks a method to be scheduled.
Definition of Scheduled(Version: spring-framework 6.1.8) package org.springframework.scheduling.annotation;
........
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
@Reflective
public @interface Scheduled {
String CRON_DISABLED = ScheduledTaskRegistrar.CRON_DISABLED; 1
String cron() default ""; 2
String zone() default ""; 3
long fixedDelay() default -1; 4
String fixedDelayString() default ""; 5
long fixedRate() default -1; 6
String fixedRateString() default ""; 7
long initialDelay() default -1; 8
String initialDelayString() default ""; 9
TimeUnit timeUnit() default TimeUnit.MILLISECONDS; 10
String scheduler() default ""; 11
}
Difference between fixedDelay and fixedRated
fixedDelay waits for the previous execution to complete PLUS the delay period before starting the next execution.
fixedRate executes at fixed intervals regardless of previous execution completion.
How to use @Schedule?
For periodic tasks, exactly one of the cron(), fixedDelay(), or fixedRate() attributes must be specified, and additionally an optional initialDelay(). For a one-time task, it is sufficient to just specify an initialDelay().
@Schedule annotated Method
The annotated method must not accept arguments. It will typically have a void return type; if not, the returned value will be ignored when called through the scheduler.
@EnableScheduling annotation
This annotation enables Spring's scheduled task execution capability. This annotation is used on @Configuration classes as follows:
@Configuration
@EnableScheduling
public class AppConfig {
...
}
Immediate Scheduling after Spring context initialization
ScheduledAnnotationBeanPostProcessor is responsible for detecting @Scheduled methods and registering them with a TaskScheduler. This BeanPostProcessor is automatically registered when we use @EnableScheduling on Spring's configuration class. This process occurs during the bean initialization phase of the Spring context. Once registered, the TaskScheduler will begin managing the execution of these tasks according to their defined schedule.
|