lundi 7 juin 2021

Should we use @Scheduled together with controller method (like @PostMaping) in SpringBoot?

I'm using SpringBatch but I cant find any document or tutorial about Spring's @Scheduled , showing it being used along side with some controller method (annotated with @GetMapping, @PostMapping).

For example, I have this controller method

    @Scheduled(cron = "0 */5 * ? * *")
    @PostMapping("/create-progress-data")
    public ResponseEntity<?> createSomething(@Request Something request) { }

I can easily create another method that do the same thing as in the body of createSomething then put it in a @Component or a Service, but between doing that and just applying @Scheduled on top of the controller method, I don't know which one is better.

I can see that:

  • Using @Scheduled : code is minimal, works just find. But we're kind of using the controller method in the wrong way. However I don't see it violates Single responsibility point in design pattern.

  • Create another method and put it in other @Component or @Service: separate the duty of the controller method and the cron job but duplicate the code.

Ps: I need to implement it like this because we need to support two ways to trigger the job. Either via api call (controller method), or periodically (with @Scheduled).

Please notice in this case the code of controller method and the expected cron job is the same.

Aucun commentaire:

Enregistrer un commentaire