java / beginner
Snippet
Scheduling Periodic Background Jobs with Scheduled Annotation
Spring simplifies task automation through the @Scheduled annotation. When combined with @EnableScheduling, Spring executes the annotated method automatically at specified time intervals (in milliseconds) without requiring manual thread creation or timers.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Component@EnableSchedulingpublic class ReportScheduler {@Scheduled(fixedRate = 5000)public void executeTaskEveryFiveSeconds() {System.out.println("Periodic health check executed.");}}
spring
Breakdown
1
@EnableScheduling
Enables Spring's background task scheduling capability in the application context.
2
@Scheduled(fixedRate = 5000)
Instructs Spring to invoke this method every 5000 milliseconds (5 seconds) continuously.
3
public void executeTaskEveryFiveSeconds()
Defines the parameterless method that contains the background routine logic.