Want to run a task every day at 8 AM using Spring Boot? Just use the @Scheduled
annotation with the right cron expression:
π
0 0 8 * * *
β this means "at 8:00 AM every day".
β
Step-by-Step Guide
1οΈβ£ Enable Scheduling
Add @EnableScheduling
in your main application class:
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SchedulerExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulerExampleApplication.class, args);
}
}
2οΈβ£ Create the Daily Scheduled Task
java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
public class DailyScheduledTask {
// Runs every day at 8 AM
@Scheduled(cron = "0 0 8 * * *")
public void scheduleTaskAtEightAM() {
System.out.println("Task running at 8 AM: " + LocalDateTime.now());
}
}
π§ Cron Breakdown
Hereβs what 0 0 8 * * *
means:
sql
| Field | Value | Description |
|--------------|-------|--------------------------|
| Seconds | 0 | At the 0th second |
| Minutes | 0 | At the 0th minute |
| Hours | 8 | At 8 AM |
| Day of month | * | Every day |
| Month | * | Every month |
| Day of week | * | Any day (MonβSun) |
π Alternate Use Case: 4 PM on the 5th Day of the Month
If you need to run a task at 4 PM on the 5th day of every month, use:
java
@Scheduled(cron = "0 0 16 5 * *")
public void scheduleTaskOnFifthDayAtFourPM() {
System.out.println("Task running at 4 PM on 5th: " + LocalDateTime.now());
}
π Timezone Support (Optional)
To make it timezone-specific:
java
@Scheduled(cron = "0 0 8 * * *", zone = "America/Toronto")
β
Summary
- βοΈ Use
@EnableScheduling
in your app. - π Use
@Scheduled(cron = "0 0 8 * * *")
for 8 AM daily. - π
Customize further using other cron expressions.
- π Add a
zone
parameter for timezone awareness.