Performance: Scheduled tasks with @Scheduled
This affects the backend task execution timing and resource usage, indirectly impacting frontend responsiveness and server load.
@Scheduled(fixedDelay = 1000)
public void lightTask() {
// quick non-blocking logic
CompletableFuture.runAsync(() -> {
// heavy processing off main scheduler thread
});
}@Scheduled(fixedDelay = 1000) public void heavyTask() throws InterruptedException { // heavy processing blocking thread Thread.sleep(5000); // task logic }
| Pattern | Thread Usage | Task Overlap | Server Load | Verdict |
|---|---|---|---|---|
| Blocking long task in @Scheduled | Single scheduler thread blocked | Possible overlap and delays | High CPU and thread contention | [X] Bad |
| Async processing inside @Scheduled | Scheduler thread free quickly | No overlap, tasks run timely | Lower CPU spikes, balanced load | [OK] Good |
@Scheduled annotation in Spring Boot?@Scheduled annotation is used to mark methods that should run automatically on a schedule without manual calls.@Scheduled?fixedRate runs the method every specified milliseconds regardless of method duration. fixedDelay waits after method finishes before next run.fixedRate = 5000 which means run every 5 seconds. @Scheduled(fixedDelay = 5000) uses fixedDelay which waits after method ends. @Scheduled(rate = 5) uses invalid attribute rate. @Scheduled(cron = "0 */5 * * * *") uses a cron expression which runs every 5 minutes.@Scheduled(fixedDelay = 3000)
public void printMessage() {
System.out.println("Hello World");
}fixedDelay = 3000 means the method runs, then waits 3 seconds after it finishes before running again.@Scheduled(fixedRate = "5000")
public void task() {
System.out.println("Running task");
}fixedRate attribute expects a long number (milliseconds), not a string. Using quotes causes a syntax error.@Scheduled. Which cron expression is correct?Pass the test and this pattern moves unknown