This short article will teach you how you can easily schedule code execution in a Spring Boot application with the least amount of effort.
Firstly, you can schedule code execution in Spring Boot via the @EnableScheduling annotation. Behind the hoods, this meta-annotation internally imports the SchedulingConfiguration.
Next, the ScheduledAnnotationBeanPostProcessor will scan the declared Spring Beans for the presence of the @Scheduled annotations. For every method that includes the @Schedule annotation, the appropriate executor thread pool will be created. It will manage the scheduled invocation of that method.
Here’s an example which will fire the execution of a method every 30 seconds:
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 MainApplication {
@Scheduled(fixedRate = 30000)
public void run() {
System.out.println("Called scheduler!");
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
On the other hand, if you want to schedule the Job after an initial delay (in ms), then you can add the initialDelay parameter in your @Scheduled method:
@Scheduled(initialDelay = 1000, fixedRate = 30000)
public void run() {
System.out.println("Called scheduler!");
}
Using different formats to schedule tasks
There are other formats you can use to define the rate of scheduling. For example, you can use the ISO Duration format:
@Scheduled(fixedDelayString = "PT10S"))
Besides, you can also use a cron expression to define the rate of scheduling. For example, to schedule the execution every 5 minutes:
@Scheduled(cron="0 */5 * ? * *")
Conditional Scheduling
In order to configure a condition on the scheduling, the recommended approach is to use the @ConditionalOnProperty annotation along with the @EnableScheduling.
In a nutshell, the @ConditionalOnProperty enables bean registration only if a system property is present and has a specific value.
@EnableScheduling
@Configuration
@ConditionalOnProperty(name = "enable.scheduling")
public class MainApplication {}
Next, to allow the scheduling of jobs, you need to provide the following property in your application.properties (or via -D) :
enable.scheduling = true
Monitoring scheduled tasks
Finally, you can use the Actuator to monitor the list of scheduled tasks.
Include the actuator dependency in your project:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
The /scheduledtasks endpoint provides details about every scheduled task within our application:
"scheduledtasks": {
"href": "http://localhost:8080/actuator/scheduledtasks",
"templated": false
},
Found the article helpful? if so please follow us on Socials