Spring Boot + JUnit

Let’s assume we need to execute a task in several minutes after a call to a web service.

ThreadPoolTaskScheduler

First we need to define a scheduler Spring Boot bean ThreadPoolTaskScheduler in a Configuration class

@Configuration
public class Config {

    @Bean
    public ThreadPoolTaskScheduler getScheduler(){
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        return scheduler;
    }

Task

Now we create the task class that implements Runnable. The code that should be executed with a time delay should be placed into the method run(). Include all parameters that should be passed as fields (for example parameter1 and parameter2).

public class WakeUpCallTask implements Runnable {

    private String parameter1;
    private String parameter2;

    public WakeUpCallTask(String parameter1, String parameter2) {
        super();
        this.parameter1= parameter1;
        this.parameter2= parameter2;
    }

    @Override
    public void run() {
        // Code that should be executed
    }

}

Schedule example

That’s how we can schedule a task to be executed in 10000ms

    @Autowired
    ThreadPoolTaskScheduler scheduler;

    @PostMapping(value = "/wake-me-up", consumes = "application/json")
    @ResponseStatus(HttpStatus.OK)
    public void scheduleCall(@RequestBody WakeMeUpRequest request) {
        scheduler.schedule(
                new WakeUpCallTask(request.getParameter1(), request.getParameter2()),
                new Date(System.currentTimeMillis() + 10000));
    }

You may also find these posts interesting: