0
0
Spring Bootframework~5 mins

Scheduled tasks with @Scheduled in Spring Boot

Choose your learning style9 modes available
Introduction

Scheduled tasks let your app do things automatically at set times. This helps with regular jobs like cleaning up data or sending reminders without you doing it manually.

You want to send daily email reminders to users.
You need to clear temporary files every hour.
You want to update data from an external source every night.
You want to run a report every Monday morning.
You want to check system health every 5 minutes.
Syntax
Spring Boot
@Scheduled(cron = "cron_expression")
public void methodName() {
    // task code here
}

The @Scheduled annotation goes above a method to run it on a schedule.

You can use cron, fixedRate, or fixedDelay to set timing.

Examples
This runs the method every 5 seconds, counting from the start of the last run.
Spring Boot
@Scheduled(fixedRate = 5000)
public void runEvery5Seconds() {
    System.out.println("Runs every 5 seconds");
}
This runs the method 10 seconds after the last run finishes.
Spring Boot
@Scheduled(fixedDelay = 10000)
public void run10SecondsAfterLastFinish() {
    System.out.println("Runs 10 seconds after last finish");
}
This runs the method every day at 9 AM using a cron expression.
Spring Boot
@Scheduled(cron = "0 0 9 * * ?")
public void runAt9AMEveryDay() {
    System.out.println("Runs every day at 9 AM");
}
Sample Program

This Spring Boot app prints a message every 3 seconds automatically. The @EnableScheduling annotation turns on scheduling support.

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

@SpringBootApplication
@EnableScheduling
public class ScheduledTaskApp {

    public static void main(String[] args) {
        SpringApplication.run(ScheduledTaskApp.class, args);
    }

    @Scheduled(fixedRate = 3000)
    public void printMessage() {
        System.out.println("Hello! This runs every 3 seconds.");
    }
}
OutputSuccess
Important Notes

Remember to add @EnableScheduling on a configuration or main class to activate scheduling.

Cron expressions are powerful but can be tricky; use online tools to build them.

Scheduled methods should not take parameters and should return void.

Summary

@Scheduled runs methods automatically on a set schedule.

You can schedule by fixed rate, fixed delay, or cron expressions.

Enable scheduling with @EnableScheduling in your Spring Boot app.