I tried, unsuccessfully, to find a way to run code after response.
In my case, a server sends me data in order to let me do my job but this action can be long (send SMS to 5000 contacts and check who received it, for example). The server expects HTTP 204 No Content response immediately to be sure that data has been received. Then my webapp will performs the action and send the status on a REST API.
My problem is: How to send the response and then execute code ?
For now I tried:
In each case, in order to test if the connection was closing before the end of my action, I call an external URL that takes 10s on purpose to answer. Each time, my server takes 10s to answer.
My servlet is simply hanging on, waiting for the end of the code.
I was unable to make the code works with Executors (new to this), but even if I got an error during the execution of the thread, I want to send HTTP 204 and handle error on another hand.
Is there an easy way to do this ?
I use background threads to poll queue tables for things that don't have to be done before the response is sent and will take longer than about 0.1 seconds. For example, an email sender thread handles sending emails in response to a user's action, like a "thanks for your order" message. In this case the servlet generates the email and appends it as a record to an Email table with a status of "ready to send", then lets the email sender thread know there's a new email ready to be sent. The email sender thread grabs the next oldest "ready to send" message, sends it, updates the table and waits for the next one. The cool part is sending an email from the main program is as easy as appending a record to the table and moving on without all that mucking about with the SMTP service each time. I have a separate but very similar thread for sending SMS. If the background process isn't able to handle the load and starts to fall behind, it's pretty easy to launch more than one as long as you're careful about making sure they don't try to grab the same record in the queue.
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