00:00

Spring Boot Scheduler

A Spring Boot Scheduler is used to execute tasks automatically at a specific time, at fixed intervals, or based on a cron expression. It is commonly used for background jobs that should run without any user interaction.


Why Do We Need a Scheduler?

In real-world applications, many operations need to run automatically in the background. Spring Boot Scheduler helps achieve this without writing complex thread or timer logic.

  • Sending scheduled emails or notifications
  • Cleaning expired data or cache
  • Generating daily or weekly reports
  • Synchronizing data with external systems
  • Running periodic system health checks

How Spring Boot Scheduler Works

Spring Boot provides built-in scheduling support using annotations. Once scheduling is enabled, Spring manages the execution of scheduled methods using a background thread pool.


Step 1: Enable Scheduling

To enable scheduling, add the @EnableScheduling annotation to the main application class.

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

Step 2: Create a Scheduled Task

Use the @Scheduled annotation on a method to make it run automatically.

Example 1: Fixed Rate

This method runs every 5 seconds, even if the previous execution has not finished.

    
    @Component
    public class TaskScheduler {
    
        @Scheduled(fixedRate = 5000)
        public void runTask() {
            System.out.println("Task running every 5 seconds");
        }
    }
    
    

Use case: Polling data or frequent background checks.


Example 2: Fixed Delay

This method runs 5 seconds after the previous execution completes.

    
    @Scheduled(fixedDelay = 5000)
    public void runWithDelay() {
        System.out.println("Task runs after 5 seconds delay");
    }
    
    

Use case: When the next task must wait until the current task finishes.


Example 3: Initial Delay

This method starts after a delay when the application starts.

    
    @Scheduled(initialDelay = 10000, fixedRate = 5000)
    public void delayedStartTask() {
        System.out.println("Task starts after 10 seconds");
    }
    
    

Use case: Waiting for application or database initialization.


Example 4: Cron Expression

Cron expressions provide more control over scheduling.

    
    @Scheduled(cron = "0 0 9 * * ?")
    public void dailyTask() {
        System.out.println("Task runs every day at 9 AM");
    }
    
    

Cron Expression Format

    second minute hour day-of-month month day-of-week
    

Common Cron Examples

Cron Expression Meaning
0 * * * * ? Every minute
0 0 * * * ? Every hour
0 0 0 * * ? Every day at midnight
0 0 9 ? * MON-FRI Weekdays at 9 AM

Thread Pool Configuration (Recommended)

By default, Spring uses a single thread for scheduling. For multiple or long-running tasks, a custom thread pool is recommended.

    
    @Configuration
    public class SchedulerConfig {
    
        @Bean
        public TaskScheduler taskScheduler() {
            ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
            scheduler.setPoolSize(5);
            scheduler.setThreadNamePrefix("scheduler-");
            return scheduler;
        }
    }
    
    

Best Practices

  • Keep scheduled tasks lightweight
  • Avoid long-running blocking operations
  • Handle exceptions properly
  • Externalize cron expressions
  • Add logging for monitoring

Externalized Cron Example

    
    @Scheduled(cron = "${scheduler.report.cron}")
    public void generateReport() {
    }
    
    

Common Mistakes to Avoid

  • Heavy database operations inside scheduler
  • Hardcoding cron expressions
  • Using a single thread for multiple tasks
  • Ignoring exception handling

Real-World Use Cases

  • Nightly batch jobs
  • Cache refresh
  • Automatic data cleanup
  • Email reminders
  • System monitoring

Summary

Spring Boot Scheduler makes it easy to run background tasks using annotations like @Scheduled. With support for fixed rate, fixed delay, and cron expressions, it provides a clean and reliable way to handle scheduled jobs in modern applications.