Spring provides annotation support for scheduling method execution using @Scheduled and @EnableScheduling.
This example shows the simple use of Spring's @Scheduled annotation for one time task. For a one-time task, it is sufficient to just specify an initialDelay().
Example
Example Bean using @Scheduled annotation
package com.logicbig.example;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalTime;
@Component
public class MyBean {
@Scheduled(initialDelay = 1000)
public void runTask() {
System.out.printf("Running scheduled task " +
" thread: %s, time: %s%n",
Thread.currentThread().getName(),
LocalTime.now());
}
}
Main class
@EnableScheduling enables Spring's scheduled task execution capability.
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
@ComponentScan
@EnableScheduling
public class ScheduledExample {
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
ScheduledExample.class);
}
}
OutputRunning scheduled task thread: pool-1-thread-1, time: 16:21:04.298963700
Before Spring version 6.1.0
Before version 6.1.0, using initialDelay alone was not supported, and it would end up with following error:
Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'runTask': Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required
Example ProjectDependencies and Technologies Used: - spring-context 6.2.12 (Spring Context)
Version Compatibility: 6.1.0 - 6.2.12 Version compatibilities of spring-context with this example:
- 6.1.0
- 6.1.1
- 6.1.2
- 6.1.3
- 6.1.4
- 6.1.5
- 6.1.6
- 6.1.7
- 6.1.8
- 6.1.9
- 6.1.10
- 6.1.11
- 6.1.12
- 6.1.13
- 6.1.14
- 6.1.15
- 6.1.16
- 6.1.17
- 6.1.18
- 6.1.19
- 6.1.20
- 6.1.21
- 6.2.0
- 6.2.1
- 6.2.2
- 6.2.3
- 6.2.4
- 6.2.5
- 6.2.6
- 6.2.7
- 6.2.8
- 6.2.9
- 6.2.10
- 6.2.11
- 6.2.12
Versions in green have been tested.
- JDK 25
- Maven 3.9.11
|