CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Spring Boot > How to Implement Scheduled Tasks in Spring Boot: A Step-by-Step Guide

How to Implement Scheduled Tasks in Spring Boot: A Step-by-Step Guide

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 · 3 min read · 0 Comments
Share: in X

Scheduled Tasks in Spring Boot are essential for automating repetitive jobs like database cleanup, report generation, or API polling. In this hands-on tutorial to implement scheduled task in Spring Boot, you’ll learn to configure and optimize scheduled tasks using Spring Boot’s @Scheduled annotation, cron expressions, and best practices for production-ready code.

Table of Contents

  • 1. Setting Up a Spring Boot Project
  • 3. Cron Jobs in Spring Boot
  • 4. Best Practices for Scheduled Tasks in Spring Boot
    • 4.1. Thread Pool Configuration
    • 4.2. Error Handling
  • 5. Common Issues and Fixes
    • 5.1. Overlapping Executions
    • 5.2. Time Zone Configuration
  • 6. Advanced: Dynamic Scheduling
  • Conclusion

1. Setting Up a Spring Boot Project

Enable scheduling in your main class with @EnableScheduling annonation.

Example:

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

2. Basic Scheduled Task Example

Use the @Scheduled annotation to run tasks at fixed intervals:

@Service
public class ReportGenerator {

    // Run every 5 seconds
    @Scheduled(fixedRate = 5000)
    public void generateReport() {
        System.out.println("Report generated at: " + new Date());
    }

    // Delay 2 seconds between executions
    @Scheduled(fixedDelay = 2000)
    public void sendNotifications() {
        System.out.println("Notifications sent at: " + new Date());
    }
}

fixedDelay vs fixedRate

  • fixedRate: Runs every N milliseconds regardless of previous execution time.
  • fixedDelay: Waits N milliseconds after the previous task finishes.

3. Cron Jobs in Spring Boot

Define complex schedules using cron expressions:

@Scheduled(cron = "0 0 8 * * MON-FRI") // Runs at 8 AM on weekdays
public void dailyDatabaseBackup() {
    System.out.println("Database backup completed.");
}

Common Cron Patterns:

ExpressionDescription
0 * * * * *Every minute
0 0/15 * * * *Every 15 minutes
0 0 12 * * ?Noon daily

4. Best Practices for Scheduled Tasks in Spring Boot

4.1. Thread Pool Configuration

Avoid overlapping executions by configuring a custom thread pool:

@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadPoolTaskScheduler threadPool = new ThreadPoolTaskScheduler();
        threadPool.setPoolSize(5);
        threadPool.setThreadNamePrefix("scheduled-task-");
        threadPool.initialize();
        taskRegistrar.setTaskScheduler(threadPool);
    }
}

Detail explanation on Spring Boot Thread Pool Configuration

4.2. Error Handling

Wrap tasks in try-catch blocks to prevent silent failures:

@Scheduled(fixedRate = 10000)
public void fetchApiData() {
    try {
        // Call external API
    } catch (Exception e) {
        logger.error("API fetch failed: ", e);
    }
}

5. Common Issues and Fixes

5.1. Overlapping Executions

Use fixedDelay instead of fixedRate for long-running tasks:

@Scheduled(fixedDelay = 30000) // Waits 30s after last execution
public void processLargeFile() {
    // Time-consuming task
}

5.2. Time Zone Configuration

Specify time zones for cron jobs:

@Scheduled(cron = "0 0 12 * * ?", zone = "Europe/Paris")
public void timeZoneTask() {
    // Runs at noon Paris time
}

6. Advanced: Dynamic Scheduling

Programmatically update tasks at runtime using ScheduledTaskRegistrar:

@Autowired
private ScheduledTaskRegistrar taskRegistrar;

public void addDynamicTask(Runnable task, String cron) {
    taskRegistrar.addCronTask(new CronTask(task, cron));
}

Conclusion

Mastering Spring Boot Scheduled Tasks empowers you to automate workflows efficiently. By leveraging the @Scheduled annotation, cron jobs, and thread pool tuning, you can build resilient and scalable applications. Experiment with the code examples above, and explore advanced use cases like dynamic scheduling.

Related Posts:

  • A Guide to Schedule Cron Jobs for Script Execution
  • Spring Boot Thread Pool Configuration: Optimizing…
  • Spring Boot Async Tasks: A Complete Guide to…
  • Inner Thread Communication in Java
  • Create Thread in Java
  • How to Set Up JaCoCo Java Test Coverage in Maven…
Tags:javaspring-boot
Was this article helpful?
← Previous ArticleCRUD Operations in JDBC: A Step-by-Step Guide
Next Article →Spring Boot Thread Pool Configuration: Optimizing Scheduled Tasks for Performance

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
© 2026 CoderSathi. All rights reserved. Privacy Policy · Sitemap