繁体   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