我有调度程序:
@Bean("one")
ThreadPoolTaskScheduler taskScheduler(){
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(5);
threadPoolTaskScheduler.setAwaitTerminationSeconds(60);
threadPoolTaskScheduler.setThreadNamePrefix("Test-");
return threadPoolTaskScheduler;
}
@Bean("two")
ThreadPoolTaskScheduler taskScheduler2(){
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(50);
threadPoolTaskScheduler.setAwaitTerminationSeconds(60);
threadPoolTaskScheduler.setThreadNamePrefix("Test2-");
return threadPoolTaskScheduler;
}
和方法:
@Scheduled(fixedRate = 1000L)
public void test() {
第二种方法:
@Scheduled(fixedRate = 1000L)
public void test2() {
如何使用具体的计划程序配置每个@Scheduled方法?
如果我这样实现:
@Slf4j
@Component
public class MyScheduler {
private final ThreadPoolTaskScheduler taskSchedulerFirst;
private final ThreadPoolTaskScheduler taskSchedulerSecond;
private final TestBean testBean;
public MyScheduler(@Qualifier("first") ThreadPoolTaskScheduler taskSchedulerFirst, @Qualifier("second")ThreadPoolTaskScheduler taskSchedulerSecond, TestBean testBean) {
this.taskSchedulerFirst = taskSchedulerFirst;
this.taskSchedulerSecond = taskSchedulerSecond;
this.testBean = testBean;
}
@PostConstruct
public void test() {
taskSchedulerFirst.scheduleAtFixedRate(testBean::test, 1000L);
taskSchedulerSecond.scheduleAtFixedRate(testBean::test2, 1000L);
}
Bouth调度程序未使用,已使用TaskExecutor:
2018-09-05 11:10:30.812 INFO 10724 --- [TaskExecutor-41] com.example.scheduling.TestBean : hz
2018-09-05 11:10:31.747 INFO 10724 --- [TaskExecutor-43] com.example.scheduling.TestBean : hz
2018-09-05 11:10:31.748 INFO 10724 --- [TaskExecutor-46] com.example.scheduling.TestBean : hz2
2018-09-05 11:10:32.747 INFO 10724 --- [TaskExecutor-45] com.example.scheduling.TestBean : hz
2018-09-05 11:10:32.748 INFO 10724 --- [TaskExecutor-48] com.example.scheduling.TestBean : hz2
2018-09-05 11:10:33.747 INFO 10724 --- [TaskExecutor-47]
但是使用TaskExecutor为什么呢?
解决方法:
TL; DR否
根据Spring scheduling,它们是TaskScheduler抽象的不同实现
> ThreadPoolTaskScheduler作为实现:
ThreadPoolTaskScheduler, can be used whenever external thread management is not a requirement. Internally, it delegates to a ScheduledExecutorService instance. ThreadPoolTaskScheduler actually implements Spring’s TaskExecutor interface as well, so that a single instance can be used for asynchronous execution as soon as possible as well as scheduled, and potentially recurring, executions.
> @Scheduled作为任务计划的注释支持
The @Scheduled annotation can be added to a method along with trigger metadata.
The simplest way to schedule tasks in Spring is to create method annotated by @Scheduled in spring managed bean.
标签:scheduler,spring,java
来源: https://codeday.me/bug/20191108/2009012.html