[英]Why is the @Async task in Spring Boot scheduler not running every 1 second
我無法理解使用@Async
注釋定義的方法的行為。 據我了解,該方法應每 1 秒執行一次。 但我認為並非如此。
@EnableAsync
@Component
public class AsyncSchedulingDemo {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//every 1 second, INSTANT start of job but waits for the first job to finish hence takes 10 seconds
//here the next execution will start after 10 seconds because the job takes 10 seconds to finish
@Scheduled(fixedRate = 1000)
public void performFixedRateTask_W_LongRunningJob() throws InterruptedException {
System.out.println("Task performed every 1 second but waits for the first one to finish before the next execution starts " + dateFormat.format(new Date()));
Thread.sleep(10000);
}
//should be executed every 1 second because of @Async
//here the next execution should start IMMEDIATELY and does NOT wait for the first one to finish
@Async
@Scheduled(fixedRate = 1000)
public void performFixedRateTask_With_Async() throws InterruptedException {
System.out.println("Async Task performed every 1 second as it does NOT wait for the first one to finish " + dateFormat.format(new Date()));
Thread.sleep(10000);
}
}
控制台日志:
Task performed every 1 second but waits for the first one to finish before the next execution starts 05/13/2020 15:54:51
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 15:54:51
Task performed every 1 second but waits for the first one to finish before the next execution starts 05/13/2020 15:55:01
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 15:55:01
Task performed every 1 second but waits for the first one to finish before the next execution starts 05/13/2020 15:55:11
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 15:55:11
===更新===
如果我完全注釋掉第一個方法並再次執行應用程序,我會看到第二個方法每秒執行一次。 為什么?? 第一種方法如何防止執行第二種方法?
控制台日志:
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 16:45:48
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 16:45:49
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 16:45:50
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 16:45:51
我認為,這是因為根據spring 文檔,用於執行@Scheduled
注釋方法的線程的默認池大小為 1:“如果您不提供 'pool-size' 屬性,則默認線程池將只有一個線。”
由於第一種方法不是@Async
,它阻塞了唯一的線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.