首页 > 解决方案 > 用于检查可用性的调度程序 Spring

问题描述

我需要向站点发送请求并获取数据,但它们可能还没有准备好。我正在考虑通过@Scheduled 解决这个问题。但问题是成功收货后,我不得不停止请求。这是正确的方法吗?如果是这样,如何终止@Scheduled任务

@Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        ResponseEntity<String> response
  = restTemplate.getForEntity(Url , String.class);
}

标签: javaspringspring-boot

解决方案


是的,可以做到。您可以使用ScheduledAnnotationBeanPostProcessor。得到成功响应后,可以调用该类的postProcessBeforeDestruction()方法。这是一个示例:

public class Scheduler {

    private final ScheduledAnnotationBeanPostProcessor processor;
    private final ApplicationContext context;

    @Autowired
    public Scheduler(ScheduledAnnotationBeanPostProcessor processor, ApplicationContext context) {
        this.processor = processor;
        this.context = context;
    }

    @Scheduled(fixedRate = 5000)
    public void doSchedule() {
        Random random = new Random();
        final int i = random.nextInt() % 5;
        // here you will put your logic to call the the stopScheduler()
        if (i == 3) {
            stopScheduler();
        }
    }

    private void stopScheduler() {
        Scheduler bean = context.getBean(Scheduler.class);
        processor.postProcessBeforeDestruction(bean, "someString");
        log.debug("Scheduler closed!");
    }
}

推荐阅读