java / beginner
Snippet
Executing Periodic Tasks with the Scheduled Annotation
Spring provides the @Scheduled annotation to run methods at fixed intervals or cron expressions without manually managing thread timers. To enable this feature in your application, you must include @EnableScheduling on a configuration class.
snippet.java
java
1
2
3
4
5
6
7
8
@Componentpublic class ReportCleanupTask {@Scheduled(fixedRate = 60000)public void cleanupOldReports() {System.out.println("Executing scheduled cleanup task every 60 seconds.");}}
spring
Breakdown
1
@Component
Registers this class as a Spring-managed bean so the framework can detect scheduled methods.
2
@Scheduled(fixedRate = 60000)
Configures the method to execute repeatedly every 60,000 milliseconds (60 seconds).
3
public void cleanupOldReports() {
Defines the task method, which must have a void return type and accept no parameters.