@Scheduled(fixedRate = 5000) public void task() { System.out.println("Task executed"); }
The fixedRate attribute schedules the method to run at a fixed interval measured from the start time of the previous execution, regardless of how long the method takes to run.
The correct cron expression for 3:30 AM daily is 0 30 3 * * ?. It means at second 0, minute 30, hour 3, every day, every month, any day of week.
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyTask { @Scheduled(fixedDelay = 1000) public void run() { System.out.println("Running task"); } }
Scheduling requires enabling with @EnableScheduling on a configuration class. Without it, @Scheduled methods won't run.
@Scheduled(fixedRate = 2000) public void longTask() throws InterruptedException { Thread.sleep(5000); System.out.println("Task done"); }
With fixedRate, the scheduler triggers the method every 2 seconds from the start time, so if the method takes longer, executions overlap.
fixedDelay waits until the previous execution finishes before scheduling the next. fixedRate schedules tasks at fixed intervals from the start time, regardless of how long the task takes.