Spring boot @Async 注解与 @Scheduled

问题描述 投票:0回答:1

请解释@Async 注解如何与@Scheduled 任务配合使用。例如,我有课:

@Configuration
@EnableScheduling
@ConditionalOnProperty(name = "scheduler.enabled", matchIfMissing = true)
@RequiredArgsConstructor
@EnableAsync
public class Scheduler {
    private final ReportService reportService;

    @Scheduled(cron = "${scheduler.create-reports.cron}")
    @Async
    public void createDailyReports() {
        // TODO: Make request to team-service to find all students id's. Then create new empty reports
        List<Long> studentIdList = new ArrayList<>();
        reportService.createEmptyDailyReports(studentIdList);
    }
}

是否需要在内部

reportService.createEmptyDailyReports
方法上使用@Async注释来异步处理整个
createDailyReports()
或在
createDailyReports()
上@Async就足够了?

在我看来,一个@Async就足够了。谢谢解释

java spring-boot asynchronous scheduled-tasks
1个回答
0
投票

基本上,

@Aysnc
注释使用SimpleAsyncTaskExecutor,它的实现是为每个任务启动一个新线程,异步执行它。

实施细节

Async 注解默认使用 SimpleAsyncTaskExecutor。正如文档中提到的,该执行器不重用线程!而是为每次调用启动一个新线程。但是,它支持并发限制。默认情况下,并发线程数是无限的。这意味着每次调用带有异步注释的方法都将使用新线程运行。

现在,使用

@Async
注释,计划方法每次都会使用新线程异步执行,这是包含更多信息的 示例

不要忘记在 Configuration 类或 Main 类中添加 @EnableAsync 和 @EnableScheduling 注释

© www.soinside.com 2019 - 2024. All rights reserved.