Spring Framework FAQ: Top Questions
35. How can you schedule tasks using Spring?
Spring provides support for scheduled tasks using @Scheduled
and TaskScheduler
.
📘 Setup:
- Enable scheduling via
@EnableScheduling
. - Annotate methods with
@Scheduled
to run periodically.
📥 Example:
@Scheduled(fixedRate = 5000)
public void pollService() {
System.out.println("Polling external service...");
}
🏆 Expected Output:
Prints message every 5 seconds.
🛠️ Use Cases:
- Regular polling of APIs or databases.
- Batch jobs or background tasks.