Spring @ Scheduled @ Async implements scheduling tasks in combination, @ scheduled @ async
The Scheduled task has been using quartz and so on before, but I noticed that Spring actually provides a simple scheduling annotation @ Scheduled, so I just want to try it out ..
The Code is as follows:
@ Component @ EnableSchedulingpublic class AsyncTaskHandlerTask {@ Scheduled (fixedDelay = 1000) public void task1 () {// output log} @ Scheduled (fixedDelay = 1000) public void task2 () {// output log }}
After you execute the command, it is completely OK, the log is printed normally, and the two tasks are also executed properly and scheduled. Well, add some business logic:
@Component@EnableSchedulingpublic class AsyncTaskHandlerTask { @Scheduled(fixedDelay = 1000) public void task1() { while(true){ .... } } @Scheduled(fixedDelay = 1000) public void task2() { while(true){ .... } }}
It's strange to start the task again. Why is the scheduled task not executed? I did not output a log test before, and I may think that the usage of the annotation is wrong... I re-added the log and re-followed the START process to find the following:
After the program enters the while endless loop, it becomes stuck and does not start another scheduled task. it can be seen from the phenomenon that @ Scheduled is a single thread synchronization startup process, so once it is blocked halfway, the entire startup process will be blocked,
Other scheduled tasks are not started. this is obviously quite strange. Most of the online tutorials are in xml configuration form. The Spring official website is very slow .. however, we can see from the xml configuration form that a thread pool needs to be configured to start a scheduled task.
Service. however, the Javaconfig format is not described. however, I found another annotation @ Async. I used this asynchronous annotation. You can specify the thread pool. after hitting the method, the method will be executed using the specified thread pool. then the solution comes:
@Component@EnableSchedulingpublic class AsyncTaskHandlerTask { @Scheduled(fixedDelay = 1000) @Async public void task1() { while(true){ .... } } @Scheduled(fixedDelay = 1000) @Async public void task2() { while(true){ .... } }}
Start again and will not be blocked again.