springboot + @scheduled multitasking concurrent

The following is about springboot + @scheduled multitasking concurrency. For details of spring's scheduled tasks (including multitasking concurrency), see Portal

I. Problems


The project is built with springboot. I want to add @ Scheduled annotation to the method to realize two timing tasks. However, it is found that two tasks are not executed concurrently, but only one task is executed before the other. Upper Code:

package com.autohome.contentplatform.tasks;
 
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
@Component
@Configurable
@EnableScheduling
public class task1 {
     @Scheduled(cron = "0/5 * *  * * ? ")
     public void startSchedule() {
         System.out.println("===========1=>");
         try {
             for(int i=1;i<=10;i++){
                 System.out.println("=1==>"+i);
                 Thread.sleep(1000);
             }
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
     }
     @Scheduled(cron = "0/5 * *  * * ? ")
     public void startSchedule2() {
         for(int i=1;i<=10;i++){
             System.out.println("=2==>"+i);
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
     }
}

The run discovery task was not executed in parallel.

Two, solve

@Component
@Configurable
@EnableScheduling
@EnableAsync
public class DemoTask {
     @Async
     @Scheduled(cron = "0/5 * *  * * ? ")
     public void startSchedule() {
         System.out.println("===========1=>");
         try {
             for(int i=1;i<=10;i++){
                 System.out.println("=1==>"+i);
                 Thread.sleep(1000);
             }
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
     }
 
    @Async
     @Scheduled(cron = "0/5 * *  * * ? ")
     public void startSchedule2() {
         for(int i=1;i<=10;i++){
             System.out.println("=2==>"+i);
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
     }
}


Annotate the class with @ EnableAsync and the method with @ Async.

 

Run it again and find that two tasks can be executed concurrently.

3, Reference:

https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html

Tags: Spring SpringBoot

Posted on Sat, 04 Apr 2020 17:40:32 -0700 by tulleh