I have a Spring boot controller which makes two service calls. The second call should occur only after 10 secs, after getting response from first call.
public SomeResponse myAction() {
res = serviceCallA();
waitFor(10) {
serviceCallB();
}
return res;
}
The action doesn't have to wait for the response from serviceCallB(), to return response. Call to serviceCallB() just has to be triggered in separate thread.
Whats the best way to implement this? I need something like a ThreadPoolTaskExecutor, but with a delay.
Sample code would awesome..
The easiest way to delay a java program is by using Thread. sleep() method. The sleep() method is present in the Thread class. It simply pauses the current thread to sleep for a specific time.
Sleep method causes current thread to pause for specific duration of time. We can use Thread's class sleep static method delay execution of java program. Here is sample code to the same. Please note that Unit of time is milliseconds for sleep method, that's why we have passed 5000 for 5 secs delay.
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 ). Spring Boot + TestNG.
Best way to execute block of code after Spring Boot application started is using PostConstruct annotation.Or also you can use command line runner for the same. 1. Using PostConstruct annotation
This interface can schedule code to run once after a specified delay or at fixed time intervals. To run a piece of code once after a delay, we can use the schedule method: The Classname::someTask part is where we specify the method that will run after the delay: To run a task at fixed time intervals, we can use the scheduleAtFixedRate method:
Define a method that will be executed after the delay. 2. Create a class that implements the Runnable interface. 3. Override run () method and call the method that you want to execute after the delay. 4.
Very straightforward answer;
SomeResponse myAction() {
res = serviceCallA();
serviceCallB();
return res;
}
@Async
void serviceCallB() {
Thread.sleep(10000) // 10 secs
// do service B call stuff
}
More on @Async with Spring also this
Beware though, since these calls will be running these serviceCallB()
logic in new threads, and if used without proper control, might cause memory issues & kill your server.
Use a promise, not the horrible Thread.sleep
from 1999 that wastes precious system resources. Your options are CompletableFuture, RxJava Publisher constructs, Spring's own Project Reactor.
Let serviceCallA
return Mono<Something>
(Project Reactor). Then:
res.delayElement(Duration.ofSeconds(10))
.doOnEach(unused -> serviceCallB())
.block();
There's probably 6 ways to do this in each library, the above being one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With