Search code examples
spring-bootspring-batchschedulejob-scheduling

Spring batch: How to change the fixed delay of a job dynamically at run time


My requirement:

I have a spring batch job with fixed delay as 5 sec. So my job will poll a web service for every 5 sec and based on the response(case when I get 200 ok status ) I need to put the current job to sleep for 30 seconds and after that it has to resume polling the web service every 5 seconds

Is there any way to configure this dynamically during run time ?? I need to change the fixed delay property in Reader part.

My sample TestJob config:

@Scheduled(fixedDelay = 5000L) // I need to change this property dynamically @ runtime 
    public void TestEventScheduler() {
        JobParameters jobParameters = new JobParametersBuilder().addLong("TestDataJobTime", System.currentTimeMillis()) 
                .toJobParameters();
        try {
            jobLauncher.run(TestDataJob, jobParameters);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Solution

  • There are many approaches you could do here:

    1. Register Trigger bean and update it every time with your delay. You can also look into CompoundTrigger to simplify your logic.

    2. Instead of using @Scheduled annotation at the end of your batch job you can have a listener or output channel which will add your batchJob once more to execution channel with specific delay.

    Also you can check similar problem's answer: Scheduling a job with Spring programmatically (with fixedRate set dynamically)