First, the question
The project uses Springboot build, wants to add @scheduled annotation to the method, realizes two timed tasks . However, running the discovery, the two task does not execute concurrently, but executes one task before executing the other. On the code:
PackageCom.autohome.contentplatform.tasks;Importorg.springframework.beans.factory.annotation.Configurable;Importorg.springframework.scheduling.annotation.EnableScheduling;Importorg.springframework.scheduling.annotation.Scheduled;Importorg.springframework.stereotype.Component, @Component @configurable@EnableScheduling Public classTask1 { @Scheduled (cron = "0/5 * * * *?") Public voidStartschedule () {System.out.println ("===========1=>"); Try { for(inti=1;i<=10;i++) {System.out.println ("=1==>" +i); Thread.Sleep (1000); } } Catch(interruptedexception e) {e.printstacktrace (); }} @Scheduled (cron = "0/5 * * * *?") Public voidStartSchedule2 () { for(inti=1;i<=10;i++) {System.out.println ("=2==>" +i); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } } }}
Running discovery tasks is not performed in parallel.
Second, the settlement
Add annotation @enableasync to the class and add annotation @async to the method.
@Component @configurable@EnableScheduling @enableasync Public classDemotask {@Async @Scheduled (cron= "0/5 * * * *?") Public voidStartschedule () {System.out.println ("===========1=>"); Try { for(inti=1;i<=10;i++) {System.out.println ("=1==>" +i); Thread.Sleep (1000); } } Catch(interruptedexception e) {e.printstacktrace (); }} @Async @Scheduled (cron= "0/5 * * * *?") Public voidStartSchedule2 () { for(inti=1;i<=10;i++) {System.out.println ("=2==>" +i); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } } }}
Run again and discover that two tasks can be executed concurrently.
Iii. References:
Https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html
Springboot + @scheduled Multitasking concurrency