在不使用 xml 注释的情况下为 spring 中的 @Scheduled 注释添加调度程序

Adding scheduler for @Scheduled annotation in spring without using xml annotations

我有几个带有注释的方法@Scheduled。对于每个注释或其中的一组,我希望使用不同的调度程序。例如:
A 组有 3 个带有 @Scheduled 注解的方法需要使用 Scheduler X.
B 组有 5 个带有 @Scheduled 注解的方法需要使用 Scheduler Y.

根据我在 Does spring @Scheduled annotated methods runs on different threads? 中读到的内容,如果未指定调度程序,那么这些方法中只有一种会 运行 一次。

我知道如何使用基于 xml 的注释来完成此连接。但是有没有一种方法可以仅使用基于 Java 的注释来完成?

可以使用 java 配置来完成。但不使用注释属性。

您可以查看 Spring API doc 以获取一些扩展示例。

例如:

 @Configuration
 @EnableScheduling
 public class AppConfig implements SchedulingConfigurer {

     @Override
     public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
         taskRegistrar.setScheduler(taskScheduler());
     }

     @Bean(destroyMethod="shutdown")
     public Executor taskScheduler() {
         return Executors.newScheduledThreadPool(42);
     }

 }

@Scheduled 组尚不支持。看到这个 open issue.

如果您想使用多个调度程序,则必须以编程方式创建和配置它们。例如:

 @Configuration
 @EnableScheduling
 public class AppConfig implements SchedulingConfigurer {

     [...]

     @Bean(destroyMethod="shutdown", name = "taskSchedulerA")
     public Executor taskSchedulerA() {
         return Executors.newScheduledThreadPool(42);
     }
     @Bean(destroyMethod="shutdown", name = "taskSchedulerB")
     public Executor taskSchedulerA() {
         return Executors.newScheduledThreadPool(42);
     }
 }


 @Service
 public class MyService {
      @Autowired @Qualifier("taskSchedulerA")
      private Executor taskSchedulerA; 
      @Autowired @Qualifier("taskSchedulerB")
      private Executor taskSchedulerB; 

      @PostConstruct
      public void schedule(){
        Executors.newScheduledThreadPool(42).schedule(new Runnable() {
          @Override
          public void run() {
            functionOfGroupA();
          }
    } , ..);

      }
 }