@Scheduled in Spring: What It Is and How It Works
@Scheduled is a Spring annotation that lets you run methods automatically at fixed intervals or specific times. It helps schedule tasks like sending emails or cleaning up data without manual triggers.How It Works
The @Scheduled annotation tells Spring to run a method on a schedule you define. Think of it like setting an alarm clock that rings at certain times, and when it rings, your method runs automatically.
You can set schedules using fixed delays, fixed rates, or cron expressions. Spring manages the timing behind the scenes, so you just write the method and add @Scheduled with your timing rules.
This is useful because it frees you from calling methods manually or writing complex timer code. Spring handles the timing and execution smoothly.
Example
This example shows a method that prints a message every 5 seconds using @Scheduled.
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTask { @Scheduled(fixedRate = 5000) public void printMessage() { System.out.println("Hello! This runs every 5 seconds."); } }
When to Use
Use @Scheduled when you want to run tasks automatically without user action. Common uses include:
- Sending reminder emails at regular intervals
- Cleaning up old files or database records nightly
- Generating reports every hour
- Polling external services periodically
It is perfect for background jobs that need to happen on a schedule inside your Spring application.
Key Points
@Scheduledruns methods automatically on a schedule.- Supports fixed delays, fixed rates, and cron expressions.
- Requires enabling scheduling with
@EnableSchedulingin your Spring config. - Runs tasks in background threads managed by Spring.
- Great for periodic background jobs inside Spring apps.
Key Takeaways
@Scheduled automates running methods at set times or intervals.@EnableScheduling in your Spring configuration.