Please explain how does @Async annotation works with @Scheduled tasks. For example, i have class:
@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);
}
}
Is it necessary to annotate inner reportService.createEmptyDailyReports
method with @Async to process whole createDailyReports()
in async or @Async on createDailyReports()
is enough?
In my mind one @Async is enough. Thanks for explanation
Basically the @Aysnc
annotation uses the SimpleAsyncTaskExecutor which is implemented to fire up a new Thread for each task, executing it asynchronously.
Async annotation uses SimpleAsyncTaskExecutor by default. As mentioned in the docs, this executor does not reuse threads!, rather it starts up a new thread for each invocation. However, it supports a concurrency limit. By default, the number of concurrent threads is unlimited. That means each invocation of a method that is annotated with Async annotation will be running with a new thread.
Now, with the @Async
annotation the scheduled method will executed asynchronously with a new thread every time, here is the example with more information
Don’t forget to add @EnableAsync and @EnableScheduling annotations in a Configuration class or Main class