A Guide to Scheduling Tasks in Spring Boot Using @Scheduled

Sahil RajputSahil Rajput
4 min read

Overview

In modern applications, there are numerous scenarios where tasks must run at specific intervals or periodically. These tasks include deleting old log files, clearing temporary data, cache management, triggering alerts or emails, and data synchronization.

Scheduled tasks can make any application more efficient and intelligent.

What is Scheduling in Spring Boot?

Spring Boot provides built-in support for task scheduling using the scheduled annotation. This annotation allows us to execute any method periodically based on a fixed rate, fixed delay, or cron expression.

Enable Support for Scheduling

To make sure Scheduling runs, first we need enable scheduling in any spring boot applications. This can be done by adding EnableScheduling annotation to a configuration class or main application class.

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

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

Different Scheduling Options

Now, there are different scheduling strategies.

1) Fixed Rate

Fixed Rate executes the annotated method at a fixed interval, counting from the start of the previous execution of same method.

@Scheduled(fixedRate = 10000)
public void fixedRateTask() {
    System.out.println("Fixed Rate -> Execution Time : " + new Date());
}

This method executes every 10 seconds, starting from the start time of previous execution.

2) Fixed Delay

Fixed Delay executes the annotated method with fixed delay after the completion of the last execution.

@Scheduled(fixedDelay = 10000)
public void fixedDelayTask() {
    System.out.println("Fixed Delay -> Execution Time : " + new Date());
}

This method waits for 10 seconds after a task finished and after that starts the next execution.

3) Initial Delay

Initial Delay waits for defined timing once application starts and then defined execution starts.

Initial Delay and Fixed Rate

once application started, this will executes after defined initial delay and then repeated executions based on fixed rate.

@Scheduled(initialDelay = 20000, fixedRate = 10000)
public void initialDelayFixedRateTask() {
    System.out.println("Initial Delay : Fixed Rate -> Execution Time : " + new Date());
}

This method waits for 20 seconds once application is started and after that executes every 10 seconds, starting from the start time of previous execution.

Initial Delay and Fixed Delay

once application started, this will executes after defined initial delay and then repeated executions based on fixed Delay.

@Scheduled(initialDelay = 20000, fixedDelay = 10000)
public void initialDelayFixedDelayTask() {
    System.out.println("Initial Delay : Fixed Delay -> Execution Time : " + new Date());
}

This method waits for 20 seconds once application is started and after that waits every 10 seconds after a task finished and after that starts the next execution.

4) Cron Expression

Cron Expression is useful when we need to set up more advanced schedules.

@Scheduled(cron = "0 0 0/1 * * *")
public void cronTask() {
    System.out.println("Cron Task -> Execution Time : " + new Date());
}

Runs at the start of every hour.

Cron format is like second, minute, hour, day of month, month, day(s) of week which we need to consider while defining any expressions.

Real Work Examples

Data Synchronization

  • Syncing data between to system (e.g. internal DB to external DB)

  • Fetching data from third party APIs (e.g. pulling weather stats every 5 minutes)

System Maintain and Clean-up

  • Deleting old log files / temporary data from system / database to free up space

  • Clearing cache periodically

Alerts and Notifications

  • Sending daily, weekly, monthly emails or sms (e.g. reminders, invoices, payment reminders)

  • Push notifications regarding events at specific timings

Report Generation

  • Generating reports from database

  • Generating usages summaries every month

Batch Processing

  • Processing large datasets in batched manner during off-peak hours

  • Migrating data periodically and creating periodic backups

  • Automating end-of-day operations

Conclusion

In this article, we explore task scheduling in Spring Boot, showing how it can improve application efficiency by automating tasks like data synchronization, system maintenance, alerts, notifications, batch processing and report generation. Spring Boot's built-in support enables scheduled tasks using fixed rates, delays, and cron expressions, making automation easy with minimal setup. We discuss various scheduling strategies and provide real-world examples to illustrate its flexibility and effectiveness in streamlining operations.

0
Subscribe to my newsletter

Read articles from Sahil Rajput directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sahil Rajput
Sahil Rajput