How to trigger a scheduled Spring Batch Job?

后端 未结 4 1449
日久生厌
日久生厌 2021-02-06 00:51

I want to be able to start my job with a REST controller, then when the job is started, it should run on a scheduled basis, until i stop it again with REST.

So this is m

4条回答
  •  猫巷女王i
    2021-02-06 01:41

    I would approach it in a way, that scheduled job runs always, but it does something only when the flag is set to true:

    @Component
    class ScheduledJob {
    
        private final AtomicBoolean enabled = new AtomicBoolean(false);
    
        @Scheduled(fixedRate = 1000)
        void execute() {
            if (enabled.get()) {
                // run spring batch here.
            }
        }
    
        void toggle() {
            enabled.set(!enabled.get());
        }
    
    }
    

    and a controller:

    @RestController
    class HelloController {
    
        private final ScheduledJob scheduledJob;
    
        // constructor
    
        @GetMapping("/launch")
        void toggle() {
            scheduledJob.toggle();
        }
    
    }
    

提交回复
热议问题