@RefreshScope stops @Scheduled task

前端 未结 4 721
心在旅途
心在旅途 2020-12-11 22:48

I have a monitoring app wherein I am running a fixedRate task. This is pulling in a config parameter configured with Consul. I want to pull in updated configuration, so I ad

4条回答
  •  星月不相逢
    2020-12-11 23:10

    I have done workaround for this kind of scenario by implementing SchedulingConfigurer interface. Here I am dynamically updating "scheduler.interval" property from external property file and scheduler is working fine even after actuator refresh as I am not using @RefreshScope anymore. Hope this might help you in your case also.

    public class MySchedulerImpl implements SchedulingConfigurer {
    
        @Autowired
        private Environment env;
    
        @Bean(destroyMethod = "shutdown")
        public Executor taskExecutor() {
            return Executors.newScheduledThreadPool(10);
        }
    
        @Override
        public void configureTasks(final ScheduledTaskRegistrar taskRegistrar) {
            taskRegistrar.setScheduler(this.taskExecutor());
            taskRegistrar.addTriggerTask(() -> {
                //put your code here that to be scheduled
            }, triggerContext -> {
                final Calendar nextExecutionTime = new GregorianCalendar();
                final Date lastActualExecutionTime = triggerContext.lastActualExecutionTime();
    
                if (lastActualExecutionTime == null) {
                    nextExecutionTime.setTime(new Date());
                } else {
                    nextExecutionTime.setTime(lastActualExecutionTime);
                    nextExecutionTime.add(Calendar.MILLISECOND, env.getProperty("scheduler.interval", Integer.class));
                }
                return nextExecutionTime.getTime();
            });
        }
    }
    

提交回复
热议问题