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:


package com.kscodes.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class TaskSchedulerApplication {
    public static void main(String[] args) {
        SpringApplication.run(TaskSchedulerApplication.class, args);
    }
}

๐Ÿ” 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.


package com.kscodes.springboot.scheduler;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class FixedRateScheduler {

    @Scheduled(fixedRate = 5000) // Every 5 seconds
    public void scheduleTask() {
        System.out.println("๐Ÿ“ข Fixed Rate Task - " + System.currentTimeMillis());
    }
}

โŒ› Option 2: Fixed Delay

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


@Scheduled(fixedDelay = 5000)
public void scheduleTaskWithDelay() {
    System.out.println("๐Ÿ“ข Fixed Delay Task - " + System.currentTimeMillis());
}

โณ Option 3: Initial Delay + Fixed Rate

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


@Scheduled(initialDelay = 3000, fixedRate = 7000)
public void scheduleWithInitialDelay() {
    System.out.println("๐Ÿ“ข Delayed Start Task - " + System.currentTimeMillis());
}

๐Ÿ“† Option 4: Cron Expression

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


@Scheduled(cron = "0 0 10 * * MON")
public void cronJob() {
    System.out.println("๐Ÿ“… Cron Task - Monday 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


@Scheduled(cron = "0 0 2 * * *") // Every day at 2 AM
public void sendDailyEmailReport() {
    // email logic
}

๐Ÿงน Delete Old Logs Weekly


@Scheduled(cron = "0 0 3 * * SUN") // Every Sunday at 3 AM
public void cleanLogs() {
    // cleanup logic
}

โš ๏ธ Handling Exceptions

By default, a thrown exception stops future executions.

Wrap your logic with try-catch to avoid interruption:


@Scheduled(fixedRate = 10000)
public void safeTask() {
    try {
        // risky task
    } catch (Exception ex) {
        System.err.println("โŒ Error in scheduled task: " + ex.getMessage());
    }
}

โš™๏ธ Async Execution of Tasks

Use @Async to run scheduled tasks in parallel.

Step 1: Enable Async


@EnableAsync
@EnableScheduling
@SpringBootApplication
public class MyApp {}

Step 2: Annotate Method


@Async
@Scheduled(fixedRate = 2000)
public void parallelTask() {
    System.out.println("๐Ÿƒ Running in background: " + Thread.currentThread().getName());
}

๐Ÿ“ Customizing Scheduling via application.yml

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


scheduler:
  cleanup-rate: 5000


@Scheduled(fixedRateString = "${scheduler.cleanup-rate}")
public void externalConfiguredTask() {
    // task
}

โœ… 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.