In Spring Boot applications, the @Scheduled
annotation provides a convenient way to execute scheduled tasks. Whether you need to run a method at fixed intervals, after a specific delay, or based on a cron expression, @Scheduled
offers flexibility and simplicity. In this tutorial, we’ll explore how to use @Scheduled
with various examples to schedule tasks in your Spring Boot application.
1. Dependencies
Make sure your pom.xml
(if using Maven) or build.gradle
(if using Gradle) includes the necessary dependencies. Spring Boot already includes many dependencies by default, but ensure you have these for scheduling:
Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
Gradle
implementation 'org.springframework.boot:spring-boot-starter'
2. Creating a Scheduled Task
Let’s create a simple Spring Boot application with a scheduled task using @Scheduled
.
2.1. Create a Spring Boot Application
First, create a new Spring Boot application. If you’re using an IDE like IntelliJ IDEA or Spring Tool Suite, you can create a new project with Spring Initializr. Otherwise, you can use Spring Initializr online.
Ensure you include the Spring Web
dependency, as we’ll create a REST endpoint to demonstrate the scheduled task.
2.2. Create a Scheduled Task Class
Next, create a Java class for your scheduled task. This class will contain methods that will be executed based on the schedule defined by @Scheduled
.
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
// Run this method every 5 seconds
@Scheduled(fixedRate = 5000)
public void executeTask() {
System.out.println("Executing scheduled task...");
// Perform your task here
}
}
In this example, executeTask()
will run every 5 seconds (fixedRate = 5000
milliseconds). Replace the // Perform your task here
comment with the logic you want to execute.
2.3. Create a REST Controller (Optional)
If you want to see the scheduled task results via a REST endpoint, create a simple controller:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
@GetMapping("/task")
public String triggerTask() {
// Endpoint to trigger the scheduled task manually
// You can call this endpoint to see the scheduled task execution
return "Scheduled task triggered manually.";
}
}
2.4. Running the Application
Now you can run your Spring Boot application. When the application starts, the executeTask()
method will run every 5 seconds, printing “Executing scheduled task…” to the console.
If you created the REST controller, you can also visit http://localhost:8080/task
to trigger the task manually and see the message.
3. Advanced Scheduling
3.1. Fixed Delay
Instead of running a task at a fixed rate, you can specify a fixed delay between the end of the last execution and the start of the next execution. Modify the executeTask()
method:
@Scheduled(fixedDelay = 5000) // Wait 5 seconds after the previous execution completes
public void executeTask() {
System.out.println("Executing scheduled task with fixed delay...");
}
3.2. Initial Delay
You can also set an initial delay before the first execution of the task. This can be useful if you want to wait for the application to fully start before running the task:
@Scheduled(initialDelay = 5000, fixedRate = 5000) // Wait 5 seconds before first execution
public void executeTask() {
System.out.println("Executing scheduled task with initial delay...");
}
3.3. Cron Expression
For more complex scheduling needs, you can use a cron expression. This allows you to define specific times or intervals for task execution. Modify the executeTask()
method:
@Scheduled(cron = "0 * * * * ?") // Run every minute
public void executeTask() {
System.out.println("Executing scheduled task with cron expression...");
}
This cron expression 0 * * * * ?
means “every minute”. You can customize it according to your requirements. There are many online cron expression generators to help you create the expression you need.
Conclusion
In this tutorial, we’ve covered how to use the @Scheduled
annotation in Spring Boot to schedule tasks. You learned how to create a simple scheduled task that runs at fixed intervals, as well as more advanced configurations such as fixed delays, initial delays, and cron expressions.
By using @Scheduled
, you can automate repetitive tasks within your Spring Boot applications, such as data synchronization, report generation, or any other background processes. This powerful annotation simplifies the scheduling of tasks, making your application more efficient and reliable.