Scheduling Tasks in Spring Boot with @Scheduled

Modern applications often need to perform background tasks automatically โ€” like sending emails, cleaning logs, syncing data, or generating reports. A simple and elegant way in Scheduling Tasks in Spring Boot is with @Scheduled Annotation.

In this guide, weโ€™ll explore how to use Spring Boot @Scheduled tasks, including:

  • Enabling scheduling
  • Using fixed rate and fixed delay
  • Writing cron expressions
  • Real-world scheduling examples
  • Error handling and async execution
Scheduling Tasks in Spring Boot with @Scheduled

โœ… Step 1: Enable Scheduling

First, annotate your main application class with @EnableScheduling:

๐Ÿ” Step 2: Use @Scheduled Annotation

You can annotate any @Component method with @Scheduled to run it automatically.

โฑ Option 1: Fixed Rate

Runs at a regular interval from the start of the previous execution.

โŒ› Option 2: Fixed Delay

Runs with a delay after the completion of the previous execution.

โณ Option 3: Initial Delay + Fixed Rate

Use initialDelay to delay the first execution, then follow fixedRate.

๐Ÿ“† Option 4: Cron Expression

For complex scheduling like “Every Monday at 10AM”:

Cron Format: second minute hour day month day-of-week
Example: "0 0/15 * * * *" โ†’ Every 15 minutes

๐Ÿ“Œ Real-World Examples

๐Ÿ’Œ Send Email Every Night

๐Ÿงน Delete Old Logs Weekly

โš ๏ธ Handling Exceptions

By default, a thrown exception stops future executions.

Wrap your logic with try-catch to avoid interruption:

โš™๏ธ Async Execution of Tasks

Use @Async to run scheduled tasks in parallel.

Step 1: Enable Async

Step 2: Annotate Method

๐Ÿ“ Customizing Scheduling via application.yml

You can define values externally using @Scheduled(${...}) and application.yml:

โœ… Summary

Scheduling Tasks in Spring Boot with @Scheduled provides a simple way to automate recurring jobs in your application. Whether it’s a cron-based job or fixed interval task, Spring gives you full control over scheduling.

In this guide, you learned following items:

  • How to enable scheduling
  • Fixed rate vs fixed delay
  • Cron expressions
  • Async tasks and exception handling

Use Spring Boot @Scheduled tasks to automate your background workflows and keep your services self-maintaining and efficient.