Home > database >  Scheduling task with parameters in Java and Springboot
Scheduling task with parameters in Java and Springboot

Time:12-13

I have a method doSomething(a, x) which I want to schedule x hours in advance. I have tried multiple setups but all seem to fail. Could anybody tell me a service structure or springboot feature which could accomplish this while also being testable?

This is my current setup in java and springboot which is failing because the fixedDelay is not constant as I don't want my tests to be delayed for x hours.

The desired result of this code would be: a is printed after x hours

The service:

@Service
public class SomeService{

    public void doSomething(int a, long x) {
        SchedulerService scheduler = new SchedulerService(a, x, this);
        scheduler.doSomethingWithA();
    }

    public void doSomethingWithA(int a) {
        System.out.println(a);
    }

}

The scheduler:

@AllArgsConstructor
public class SchedulerService {

    private int a;
    private final long x;

    private transient SomeService someService;

    @Scheduled(fixedDelay = x)
    public void doSomethingWithA() {
        someService.doSomethingWithA(a);
    }

}

Of course the actual service is far more complex with database access etc. and the x hours is actually 10 years, but I think you get the idea.

Any help would be greatly appreciated

CodePudding user response:

Spring v3.2.2 has added String parameters to the original 3 long parameters to handle this. fixedDelayString, fixedRateString and initialDelayString are now available too.

@Scheduled(fixedDelayString = "${my.fixed.delay.prop}")
public void doSomethingWithA() {

}
  • Related