以编程方式使用 Spring 安排作业(动态设置 fixedRate)

新手上路,请多包涵

目前我有这个:

 @Scheduled(fixedRate=5000)
public void getSchedule(){
   System.out.println("in scheduled job");
}

我可以将其更改为使用对属性的引用

@Scheduled(fixedRateString="${myRate}")
public void getSchedule(){
   System.out.println("in scheduled job");
}

但是,我需要使用以编程方式获得的值,以便可以在不重新部署应用程序的情况下更改计划。什么是最好的方法?我意识到使用注释可能是不可能的……

原文由 NimChimpsky 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 644
2 个回答

使用 Trigger 您可以即时计算下一次执行时间。

像这样的东西应该可以解决问题(改编自 @EnableScheduling 的 Javadoc ):

 @Configuration
@EnableScheduling
public class MyAppConfig implements SchedulingConfigurer {

    @Autowired
    Environment env;

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }

    @Bean(destroyMethod = "shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(100);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
        taskRegistrar.addTriggerTask(
                new Runnable() {
                    @Override public void run() {
                        myBean().getSchedule();
                    }
                },
                new Trigger() {
                    @Override public Date nextExecutionTime(TriggerContext triggerContext) {
                        Calendar nextExecutionTime =  new GregorianCalendar();
                        Date lastActualExecutionTime = triggerContext.lastActualExecutionTime();
                        nextExecutionTime.setTime(lastActualExecutionTime != null ? lastActualExecutionTime : new Date());
                        nextExecutionTime.add(Calendar.MILLISECOND, env.getProperty("myRate", Integer.class)); //you can get the value from wherever you want
                        return nextExecutionTime.getTime();
                    }
                }
        );
    }
}

原文由 ach 发布,翻译遵循 CC BY-SA 3.0 许可协议

您还可以为此使用 Spring 表达式语言 (SpEL)。

一旦初始化此值,您将无法更新此值。

 @Scheduled(fixedRateString = "#{@applicationPropertyService.getApplicationProperty()}")
public void getSchedule(){
   System.out.println("in scheduled job");
}

@Service
public class ApplicationPropertyService {

    public String getApplicationProperty(){
        //get your value here
        return "5000";
    }
}

原文由 Sagar Ahuja 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题