java / beginner
Snippet
Executing Recurring Tasks Automatically with Scheduled Cron Jobs
The @Scheduled annotation allows you to run background operations periodically without writing custom thread timers. By defining a fixedRate or cron expression, Spring schedules the method execution on an internal task executor asynchronously from HTTP traffic.
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 CacheCleanupTask {@Scheduled(fixedRate = 60000)public void purgeStaleEntries() {System.out.println("Clearing expired cache entries from memory...");}}
spring
Breakdown
1
@EnableScheduling
Activates Spring's background task scheduling capability across all application components.
2
@Scheduled(fixedRate = 60000)
Runs the annotated method every 60,000 milliseconds (1 minute) from task invocation start.