簡體   English   中英

Spring-boot @Async不與@Scheduled一起運行

[英]Spring-boot @Async not running with @Scheduled

我已經使用了本教程它是github項目 ,是此SSCCE的基礎。

由於未知原因,從@Scheduled方法運行的標記為@Async方法始終同步執行。

我正在尋找一種解決方案或解決方法,以使performTask()的代碼異步運行。

下面的類:

Application.java

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class Application implements AsyncConfigurer{

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }

    @Override
    @Bean(name="asyncExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
        exec.setMaxPoolSize(Runtime.getRuntime().availableProcessors()*2);
        exec.setThreadGroupName("MyCustomExecutor");
        exec.setWaitForTasksToCompleteOnShutdown(true);
        exec.setBeanName("asyncExecutor");
        exec.initialize();
        return exec;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}

MyAsyncService.java

@Service
public class MyAsyncService {

    static AtomicInteger taskNoCounter = new AtomicInteger();

    public MyAsyncService() {
    }

    @Async("asyncExecutor")
    public void performTask() {
        int delayMs = (int) (System.currentTimeMillis()%1000+1000);
        int taskNo = taskNoCounter.incrementAndGet();
        String taskInfo = "MyAsyncTask [taskNo=" + taskNo + ", delayMs=" + delayMs + ", threadId="+Thread.currentThread().getId()+"]";
        System.out.println("+ start " +taskInfo);
        try {
            Thread.sleep(delayMs);
        } catch (InterruptedException e) {
            // empty on purpose
        }
        System.out.println("- end   " +taskInfo);
    }

}

ScheduledTasks.java

@Component
public class ScheduledTasks {

    @Autowired
    MyAsyncService service;

    @Scheduled(fixedRate = 1000)
    public void reportCurrentTime() {
        for (int i=0; i<20; i++) {
            service.performTask();
        }

    }
}

產生以下同步結果:

+ start MyAsyncTask [taskNo=1, delayMs=1874, threadId=16]
- end   MyAsyncTask [taskNo=1, delayMs=1874, threadId=16]
+ start MyAsyncTask [taskNo=2, delayMs=1749, threadId=16]
- end   MyAsyncTask [taskNo=2, delayMs=1749, threadId=16]
+ start MyAsyncTask [taskNo=3, delayMs=1498, threadId=16]
- end   MyAsyncTask [taskNo=3, delayMs=1498, threadId=16]
+ start MyAsyncTask [taskNo=4, delayMs=1997, threadId=16]
- end   MyAsyncTask [taskNo=4, delayMs=1997, threadId=16]
+ start MyAsyncTask [taskNo=5, delayMs=1994, threadId=16]

問題不在於設置ThreadPoolTaskExecutorcorePoolSize屬性。

默認情況下, corePoolSize1 ,並且僅當隊列已滿時,線程數量才會增加。 由於我的隊列是無限的,因此池中再也沒有創建其他線程。

我最終做了:

exec.setCorePoolSize(Runtime.getRuntime().availableProcessors()+1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM