It is a memorandum because I tried periodic execution and asynchronous processing with Spring Boot.
OpenJDK 11 Spring Boot 2.2.1
I referred to here. How to periodically execute tasks in Spring Boot
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Scheduled(fixedRate = 10000)
public void scheduledTask() {
this.doTask();
}
Use the Scheduled annotation.
Async annotations can be used for asynchronous processing.
@EnableAsync
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Async
public void doTask() {
NormalTask normalTask = new NormalTask();
normalTask.do();
}
When the doTask method is called, the process is executed in another thread.
I thought that this combination would allow periodic execution → asynchronous processing, but the combination of Scheduled and Async does not result in asynchronous processing.
@Async
public void doTask() {
NormalTask normalTask = new NormalTask();
normalTask.do();
}
@Scheduled(fixedRate = 10000)
public void scheduled() {
this.doTask();
}
In the above example, Async doesn't work and normalTask.do () is blocked.
The method with Scheduled annotation creates Runnable and processes it in another thread, but Async does not work at this time. ScheduledThreadPoolExecutor, which manages periodic execution, seems to block until the end of Runnable's run () (to calculate the next periodic execution time from the end).
Therefore, Scheduled and Async annotation cannot be used together.
It was solved by creating another thread in Runnable created by Scheduled and executing the process in it. I think that there is no problem because Runnable created by Scheduled ends as soon as another thread for asynchronous processing is created.
AsyncTask.java
public class AsyncTask implements Runnable {
@Override
public void run() {
// Do some task
}
}
public void doTask() {
AsyncTask asyncTask = new AsyncTask();
Thread newThread = new Thread(asyncTask);
newThread.start();
}
@Scheduled(fixedRate = 10000)
public void scheduled() {
this.doTask();
}
If you have any suggestions, please feel free to contact us.
How to periodically execute tasks in Spring Boot using @Scheduled and @Async together?
Recommended Posts