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(); } }; }
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
