0 day streak
java / intermediate
Snippet

Automated Task Scheduling with @Scheduled

Using @Scheduled allows you to execute methods at specific intervals or times. In this example, the method runs every day at 2:00 AM using a cron expression.

snippet.java
java
1
2
3
4
5
6
7
8
@Component
public class CleanupTask {
@Scheduled(cron = "0 0 2 * * *")
public void runDailyCleanup() {
// Logic to delete old temporary files
System.out.println("Cleanup started...");
}
}
spring
Breakdown
1
@Scheduled(cron = "0 0 2 * * *")
Defines the schedule using cron format: second, minute, hour, day, month, day of week.
2
public void runDailyCleanup()
The logic inside this method will be triggered automatically by Spring's task scheduler.