In this post, we will explore the creation of a schedule within a Spring Boot application. The process of setting up a scheduler is elucidated through a straightforward scheduler application demonstration. This article provides a step-by-step guide on how to establish a scheduler in a Spring Boot application, allowing for the automated execution of tasks at specified intervals.
Spring Boot simplifies the creation of schedulers compared to other Java applications, streamlining the process significantly. In contrast to the complexity associated with setting up schedulers in traditional Java applications, Spring Boot’s approach is more straightforward. The scheduler in a Spring Boot application operates as a distinct and manageable process, offering enhanced control and ease of use in implementing scheduled tasks. This design choice contributes to the overall simplicity and efficiency of scheduling operations within Spring Boot applications.
The Spring Boot scheduler simplifies the construction of a scheduler into three straightforward steps. Any Spring Boot application can initiate a scheduler by following these three simple steps:
- Add the @EnableScheduling annotation to the Spring Boot application’s main class or configuration class.
- Add the @Configuration annotation to the scheduler configuration class.
- The annotation @Scheduled should be used on the scheduler task methods.
Step 1: Add the @EnableScheduling annotation to the Spring Boot application’s main class
To activate the scheduler in a Spring Boot application, use the @EnableScheduling
annotation. This annotation directs the Spring Boot application to set up and enable the necessary environment for executing one or more schedulers. It can be seamlessly incorporated into any scheduler configuration class, including the primary class of a Spring Boot application, allowing for flexible and convenient scheduling integration.
When the @EnableScheduling
annotation is added to the main class of a Spring Boot application, the scheduler environment is established before the application launch. This environment remains accessible throughout the entire Spring Boot application lifecycle. Conversely, if the @EnableScheduling
annotation is added to a scheduler configuration class, the scheduler can only be utilized within that specific class.
It’s crucial to note that the @Scheduled
annotation settings, specifying the scheduling parameters for tasks, must be declared within the scheduler configuration class. If these settings are made outside of the scheduler configuration class, the scheduler won’t be invoked as intended.
The example below illustrates how to configure the @EnableScheduling
annotation in the main class of a Spring Boot application.
SpringBootSchedulerApplication.java
package com.test; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class SpringBootSchedulerApplication { public static void main(String[] args) { SpringApplication.run(SpringBootSchedulerApplication.class, args); } }
Step 2: Add the @Configuration annotation to the scheduler configuration class
Scheduler tasks are set up through the scheduler configuration class, where Java methods representing the tasks are added. These methods are executed when the scheduler triggers at specified time intervals.
To configure the scheduler configuration class as a Spring Boot bean, the @Configuration
annotation should be applied. This annotation ensures that the class is recognized as a Spring Boot bean and is loaded at the start of the Spring Boot application. Consequently, the scheduler runs automatically at the application’s initiation.
Failure to include the @Configuration
annotation results in the Spring Boot configuration class not being treated as a bean, thus failing to load in the scheduler’s dependency injection. Therefore, it is imperative to add the @Configuration
annotation to the Spring Boot scheduler configuration class for proper functionality.
SchedulerConfiguration.java
package com.test; import org.springframework.context.annotation.Configuration; @Configuration public class SchedulerConfiguration { }
Step 3: Add annotation @Scheduled on the scheduler task methods.
Scheduler tasks encompass the activities executed when the scheduler is invoked, typically achieved through the invocation of Java methods. These methods are adorned with the @Scheduled
annotation, which accommodates scheduler configurable parameters.
In Spring Boot applications, diverse scheduler types are supported. The FixedRate scheduler ensures execution at specified time intervals, with the second task triggered at the designated interval, regardless of the completion status of the first task. The FixedRate annotation’s parameter maintains the time gap between two invocations.
Conversely, the FixedDelay scheduler enforces a fixed delay between two scheduler executions. If the first task takes longer to complete, the second task patiently waits until the former concludes, then delays for the configured time before initiating. This approach ensures no overlapping between two scheduler invocations.
The Cron scheduler provides flexibility through the configuration of a scheduler using a cron expression. The scheduler adheres to the specified cron expression, offering a tailored method for scheduling execution.
The subsequent example illustrates the configuration of a scheduler task, where the method is called every 5 seconds, outputting a log to the console window.
SchedulerConfiguration.java
package com.test; import java.text.SimpleDateFormat; import java.util.Calendar; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.Scheduled; @Configuration public class SchedulerConfiguration { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); @Scheduled(fixedRate = 5000) public void schedule() throws Exception { System.out.println("Scheduler executed on " + sdf.format(Calendar.getInstance().getTime()) + "\n"); } }
Step 4: Run the Scheduler
Upon launching the Spring Boot application, the scheduler initiates its execution. The scheduler task method is invoked regularly, adhering to the time interval specified in the scheduler configuration class. In the provided example, the scheduler task log is automatically printed every 5 seconds. The console log output is illustrated as follows:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.7.3) 2023-03-09 15:49:04.386 INFO 4564 --- [ main] c.test.SpringBootSchedulerApplication : Starting SpringBootSchedulerApplication using Java 17.0.4 on DESKTOP-1 with PID 4524 (C:\workspace\\SpringBootScheduler\target\classes started by Admin in C:\workspace\\SpringBootScheduler) 2023-03-09 15:49:04.390 INFO 4564 --- [ main] c.test.SpringBootSchedulerApplication : No active profile set, falling back to 1 default profile: "default" 2023-03-09 15:49:05.668 INFO 4564 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2023-03-09 15:49:05.681 INFO 4564 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2023-03-09 15:49:05.681 INFO 4564 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.65] 2023-03-09 15:49:05.854 INFO 4564 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2023-03-09 15:49:05.854 INFO 4564 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1314 ms 2023-03-09 15:49:06.368 INFO 4564 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' Scheduler executed on 2023-03-09 15:49:06.389 2023-03-09 15:49:06.390 INFO 4564 --- [ main] c.test.SpringBootSchedulerApplication : Started SpringBootSchedulerApplication in 2.488 seconds (JVM running for 3.409) Scheduler executed on 2023-03-09 15:49:11.397 Scheduler executed on 2023-03-09 15:49:16.385 Scheduler executed on 2023-03-09 15:49:21.399 Scheduler executed on 2023-03-09 15:49:26.392 Scheduler executed on 2023-03-09 15:49:31.397