@RefreshScope停止@Scheduled任务

时间:2018-05-21 00:05:05

标签: spring spring-cloud spring-cloud-consul

我有一个监控应用程序,其中我正在运行fixedRate任务。这是拉入Consul配置的配置参数。我想引入更新的配置,所以我添加了@RefreshScope。但是只要我更新Consul上的配置值,fixedRate任务就会停止运行。

@Service
@RefreshScope
public class MonitorService {

    @Autowired
    private AppConfig appConfig;

    @PostConstruct
    public void postConstRun() {
        System.out.println(appConfig.getMonitorConfig());
    }

    @Scheduled(fixedRate = 1000)
    public void scheduledMonitorScan() {
        System.out.println("MonitorConfig:" + appConfig.getMonitorConfig());
    }
}

AppConfig类只有一个String参数:

@Configuration
@Getter
@Setter
public class AppConfig {

    @Value("${monitor-config:default value}")
    private String monitorConfig;
}

一旦我更新了consul中的值,计划任务就会停止运行(以sheduledMonitorScan方法显示)停止显示。

4 个答案:

答案 0 :(得分:2)

我已成功使用RefreshScopeRefreshedEvent从领事配置服务器获取并覆盖了值

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@RefreshScope
public class AlertSchedulerCron implements ApplicationListener<RefreshScopeRefreshedEvent> {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Value("${pollingtime}")
    private String pollingtime;
    
    /*
     * @Value("${interval}") private String interval;
     */
    @Scheduled(cron = "${pollingtime}")
    //@Scheduled(fixedRateString = "${interval}" )
    public void task() {

        System.out.println(pollingtime);
        System.out.println("Scheduler (cron expression) task with duration : " + sdf.format(new Date()));
    }

    @Override
    public void onApplicationEvent(RefreshScopeRefreshedEvent event) {
        // TODO Auto-generated method stub
        
    }

    
}

答案 1 :(得分:1)

我已经通过实现SchedulingConfigurer接口完成了针对这种情况的解决方法。 在这里,我正在从外部属性文件动态更新“ scheduler.interval”属性,并且即使在执行器刷新后,调度程序也能正常工作,因为我不再使用@RefreshScope。 希望这对您有帮助。

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

答案 2 :(得分:1)

这是我们解决此问题的方法。

/**
 * Listener of Spring's lifecycle to revive Scheduler beans, when spring's
 * scope is refreshed.
 * <p>
 * Spring is able to restart beans, when we change their properties. Such a
 * beans marked with RefreshScope annotation. To make it work, spring creates
 * <b>lazy</b> proxies and push them instead of real object. The issue with
 * scope refresh is that right after refresh in order for such a lazy proxy
 * to be actually instantiated again someone has to call for any method of it.
 * <p>
 * It creates a tricky case with Schedulers, because there is no bean, which
 * directly call anything on any Scheduler. Scheduler lifecycle is to start
 * few threads upon instantiation and schedule tasks. No other bean needs
 * anything from them.
 * <p>
 * To overcome this, we had to create artificial method on Schedulers and call
 * them, when there is a scope refresh event. This actually instantiates.
 */
@RequiredArgsConstructor
public class RefreshScopeListener implements ApplicationListener<RefreshScopeRefreshedEvent> {
    private final List<RefreshScheduler> refreshSchedulers;

    @Override
    public void onApplicationEvent(RefreshScopeRefreshedEvent event) {
        refreshSchedulers.forEach(RefreshScheduler::materializeAfterRefresh);
    }
}

因此,我们定义了一个接口,该接口不执行任何特殊操作,但允许我们调用刷新的作业。

public interface RefreshScheduler {
    /**
     * Used after refresh context for scheduler bean initialization
     */
    default void materializeAfterRefresh() {
    }
}

这是实际的作业,其参数from.properties可以刷新。

public class AJob implements RefreshScheduler {
    @Scheduled(cron = "${from.properties}")
    public void aTask() {
        // do something useful
    }
}

答案 3 :(得分:1)

我的解决方案包括听EnvironmentChangeEvent

@Configuration
public class SchedulingSpringConfig implements ApplicationListener<EnvironmentChangeEvent>, SchedulingConfigurer {

  private static final Logger LOGGER = LoggerFactory.getLogger(SchedulingSpringConfig.class);

  private final DemoProperties demoProperties;

  public SchedulingSpringConfig(DemoProperties demoProperties) {
    this.demoProperties = demoProperties;
  }

  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    LOGGER.info("Configuring scheduled task with cron expression: {}", demoProperties.getCronExpression());
    taskRegistrar.addTriggerTask(triggerTask());
    taskRegistrar.setTaskScheduler(taskScheduler());
  }

  @Bean
  public TriggerTask triggerTask() {
    return new TriggerTask(this::work, cronTrigger());
  }

  private void work() {
    LOGGER.info("Doing work!");
  }

  @Bean
  @RefreshScope
  public CronTrigger cronTrigger() {
    return new CronTrigger(demoProperties.getCronExpression());
  }

  @Bean
  public ThreadPoolTaskScheduler taskScheduler() {
    return new ThreadPoolTaskScheduler();
  }

  @Override
  public void onApplicationEvent(EnvironmentChangeEvent event) {
    if (event.getKeys().contains("demo.config.cronExpression")) {
      ScheduledTasksRefresher scheduledTasksRefresher = new ScheduledTasksRefresher(triggerTask());
      scheduledTasksRefresher.afterPropertiesSet();
    }
  }
}

然后我使用ContextLifecycleScheduledTaskRegistrar重新创建任务。

public class ScheduledTasksRefresher extends ContextLifecycleScheduledTaskRegistrar {

  private final TriggerTask triggerTask;

  ScheduledTasksRefresher(TriggerTask triggerTask) {
    this.triggerTask = triggerTask;
  }

  @Override
  public void afterPropertiesSet() {
    super.destroy();
    super.addTriggerTask(triggerTask);
    super.afterSingletonsInstantiated();
  }
}

属性定义:

@ConfigurationProperties(prefix = "demo.config", ignoreUnknownFields = false)
public class DemoProperties {

  private String cronExpression;

  public String getCronExpression() {
    return cronExpression;
  }

  public void setCronExpression(String cronExpression) {
    this.cronExpression = cronExpression;
  }
}

主要定义:

@SpringBootApplication
@EnableConfigurationProperties(DemoProperties.class)
@EnableScheduling
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}