Spring / Spring Boot 4 Basics Interview Questions
How do you schedule tasks in Spring Boot 4 with @Scheduled?
Spring Boot 4 provides task scheduling via @EnableScheduling and @Scheduled annotations. In Boot 4, the auto-configuration for task scheduling supports multiple TaskDecorator beans, enabling better observability and context propagation.
// Enable scheduling: @SpringBootApplication @EnableScheduling public class App { ... } @Service public class ReportScheduler { // Fixed rate: every 60 seconds (interval from start of last execution) @Scheduled(fixedRate = 60_000) public void generateHourlyMetrics() { metricsService.compute(); } // Fixed delay: 30 seconds AFTER last execution completes @Scheduled(fixedDelay = 30_000) public void cleanExpiredSessions() { sessionService.evictExpired(); } // Cron expression: every day at 2:30 AM @Scheduled(cron = "0 30 2 * * *") public void dailyReport() { reportService.generateDailyReport(); } // Cron with zone: @Scheduled(cron = "0 0 8 * * MON-FRI", zone = "Europe/London") public void morningDigest() { digestService.send(); } // Initial delay: wait 5s after startup before first run @Scheduled(initialDelay = 5_000, fixedRate = 60_000) public void warmUpCache() { cacheService.preload(); } } # Cron syntax: second minute hour day-of-month month day-of-week # "0 */5 * * * *" = every 5 minutes # "0 0 * * * *" = every hour on the hour # "0 0 9-17 * * MON-FRI" = every hour 9am-5pm Mon-Fri # Spring Boot 4: multiple TaskDecorator beans supported # (propagates MDC logging context and security context to scheduled threads) @Bean public TaskDecorator mdcTaskDecorator() { return runnable -> () -> { MDC.put("task", "scheduled"); try { runnable.run(); } finally { MDC.clear(); } }; }
More Related questions...