I am using a Spring MVC controller and want to start the execution of a task in a new thread. However the task should not start immediately but only after the response has been sent to the client.
The sequence - in strict temporal order:
ResponseEntity ...
/ client receives HTTP status 200 OK.How do I achieve this?
I wanted to use Spring's async abstraction by calling a method annotated with @Async, but it does not guarantee that the new thread waits for the response to be sent first.
You can use an interceptor for that. The order of events for handling a request in Spring MVC is:
The above is over simplified and is just aimed at showing that interceptor afterCompletion
methods are called after the response has been sent to client, with following signature :
void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex)
throws Exception
In that method, you can test the occurence of an exception and the correctness of the response (ex == null && response.getStatus() == HttpServletResponse.SC_OK
) before starting your processing.
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