简体   繁体   English

不要在某台机器上运行Spring @Scheduled任务

[英]Do not run Spring @Scheduled task on certain machine

Our web app has few scheduled tasks and we like this feature of Spring so much, many have started relying on it. 我们的网络应用程序几乎没有计划任务,我们非常喜欢Spring的这个功能,许多人已经开始依赖它了。 We have a 'pilot' machine which shares the same configuration/db as prod machines. 我们有一台“试用”机器,与prod机器共享相同的配置/数据库。 Since this machine points to the same db as prod machines, when it runs a scheduled task - it may affect prod data. 由于此机器指向与prod机器相同的db,因此当它运行计划任务时 - 它可能会影响prod数据。 Is there a way to not run Spring Scheduled task on this machine? 有没有办法不在这台机器上运行Spring Scheduled任务? We thought of relying on the machine name, but dont want to introduce a check each time a task starts. 我们考虑过依赖机器名称,但不想在每次任务开始时都引入检查。 Any suggestions? 有什么建议?

With Spring 3.1 Profiles it will be really easy, but here is a way you can do it in Spring 3.0. 使用Spring 3.1 Profiles它会非常简单,但是这里有一种方法可以在Spring 3.0中实现。

In your context: 在您的上下文中:

<task:annotation-driven executor="taskExecutor" scheduler="configScheduler"/>
<task:scheduler id="taskScheduler"/>
<task:executor id="taskExecutor"/>

Use @Bean to define configScheduler , using a dummy scheduler if a system property noScheduler is set. 如果设置了系统属性noScheduler则使用@Bean定义configScheduler ,使用虚拟调度程序。

@Configuration
public class SchedulerConfig {
  @Resource(name="taskScheduler")
  ThreadPoolTaskScheduler taskScheduler;

  @Bean
  ThreadPoolTaskScheduler configScheduler() {
      ThreadPoolTaskScheduler scheduler = 
        System.getProperty("noScheduler") == null : taskScheduler ?
          new ThreadPoolTaskScheduler() {
              @Override public ScheduledFuture schedule(Runnable task, Trigger trigger) { return null; }  // Cron
              @Override public ScheduledFuture scheduleAtFixedRate(Runnable task, long period) { return null; }
              @Override public ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay) { return null; }
          };

      return scheduler;
    }
  } 

使用Spring 3.1,您将获得可能对您有所帮助的配置文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM