Spring handles scheduled and periodic task execution through the @Scheduled annotation, which lets a method run on a fixed interval, a delay, or a cron expression.
Key Points: • @EnableScheduling on a configuration class turns on Spring's task scheduler. • fixedRate runs the method at a constant interval regardless of how long the previous run took; fixedDelay waits for the previous run to finish first. • The cron attribute supports full cron expressions for calendar-based schedules (e.g. nightly at 2am). • By default, all @Scheduled methods share a single thread, so a slow task can delay others unless a custom TaskScheduler with a thread pool is configured. • @Async, combined with @EnableAsync, lets long-running tasks run on separate threads instead of blocking the caller.
Example: A nightly cleanup job that deletes expired records can be scheduled with @Scheduled(cron = "0 0 2 * * *") to run every day at 2am without any external cron setup.
Code Example:
@Configuration
@EnableScheduling
public class SchedulingConfig {
}
@Component
public class CleanupJob {
@Scheduled(cron = "0 0 2 * * *")
public void purgeExpiredRecords() {
// cleanup logic
}
}Interview Tip: A concise interview answer is:
"I use @Scheduled methods, enabled with @EnableScheduling, to run tasks on a fixed rate, fixed delay, or cron expression without an external scheduler. Since all scheduled tasks share one thread by default, I configure a custom TaskScheduler with a thread pool, or use @Async, when tasks need to run in parallel."