WBLord
WBLord

Reputation: 1025

sheduler for checking availability Spring

I need to send a request to the site and get data, but they may not be ready. I was thinking of solving this problem via @Scheduled. But the problem is that after a successful receipt, I have to stop requesting. Is this the right approach? If so, how to terminate @Scheduled task

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

Upvotes: 0

Views: 220

Answers (1)

Mukit09
Mukit09

Reputation: 3399

Yep, it can be done. You can use ScheduledAnnotationBeanPostProcessor. After getting the success response, you can call the postProcessBeforeDestruction() method of the class. Here is a sample:

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!");
    }
}

Upvotes: 2

Related Questions