Do not run Spring @Scheduled task on certain machine

ぐ巨炮叔叔 提交于 2019-12-07 10:06:05

问题


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?


回答1:


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;
    }
  } 



回答2:


With Spring 3.1, you'll get profiles, which might help you out.



来源:https://stackoverflow.com/questions/6848965/do-not-run-spring-scheduled-task-on-certain-machine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!