簡體   English   中英

在春季中為@Scheduled注釋添加調度程序,而無需使用xml注釋

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

我有幾種使用@Scheduled注釋的方法。 對於每個注釋或一組注釋,我希望使用不同的調度程序。 例如:
組A有3種帶有@Scheduled批注的方法,它們需要使用SchedulerX。
B組有5種帶有@Scheduled注釋的方法,它們需要使用SchedulerY。

從我的閱讀文章中, spring @Scheduled注釋方法是否可以在不同線程上運行? ,如果未指定調度程序,則一次僅運行這些方法之一。

我知道如何使用基於xml的注釋完成此連接。 但是,有沒有一種方法可以僅使用基於Java的注釋來完成?

可以使用java config完成。 但是不使用注釋屬性。

您可以查看Spring API文檔中的一些擴展示例。

例如:

 @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組。 看到這個未解決的問題

如果要使用多個調度程序,則必須以編程方式創建和配置它們。 例如:

 @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();
          }
    } , ..);

      }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM