java - 在spring中为@Scheduled注解添加调度器,而不使用xml注解

标签 java spring annotations scheduled-tasks scheduler

我有几个带有注释@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();
          }
    } , ..);

      }
 }

关于java - 在spring中为@Scheduled注解添加调度器,而不使用xml注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43605444/

相关文章:

java - 从 1.3.x 升级到 1.4.0 后,Spring boot ssl 配置损坏

java - 如何在Spring + tomcat 7 + MySQL中使用数据源配置p6spy

spring - 如果有@Entity,为什么需要 "annotatedClasses"?

html - 图像不显示在使用 Spring Boot、 Flying Saucer 和 Thymeleaf 的 PDF 模板中

java - 使用 itext 将签名应用于 pdf 后出现 "The document has been altered or corrupted since the signature was applied"错误

java - 两个相同的程序,只有一个可以编译(java7)

java - Windows:移动先前映射到内存中的文件失败

java - Hibernate 多对多级联删除

java - 使用 @Component 默认 Autowiring

java - android 内部存储写入文件后没有文件