简体   繁体   中英

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. We have a 'pilot' machine which shares the same configuration/db as prod machines. Since this machine points to the same db as prod machines, when it runs a scheduled task - it may affect prod data. Is there a way to not run Spring Scheduled task on this machine? 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.

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.

@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,您将获得可能对您有所帮助的配置文件

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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