11

is it possible in rails 2.3.X to start a new chain of commands after a request has been rendered and returned to the requestor?

I need that feature in order to work with an asynchronous API on the other side: They expect a response to their request and after that response is done my rails app should send a new http-request to them (post something to their API)...

What are the possibilities here? Is there something like a after_render hook? Should I make use of threads or background tasks and how could this be done?

I would be very glad for some solutions :-)

Kind regards

UPDATE: The Return-Code (eg. 200) should be sent to the requestor before the other calls are executed

Bijan
  • 25,559
  • 8
  • 79
  • 71

5 Answers5

12

The easiest thing to do is spawn a new thread. This is assuming that it is a lightweight call and you don't need advanced error logging or retry logic.

Thread.new do
  puts  "call the api"
end
Aaron Scruggs
  • 712
  • 1
  • 4
  • 10
  • yeah good idea... I am now using https://github.com/tra/spawn which does exactly this as a rails plugin – Bijan Dec 06 '10 at 13:27
3

The two most popular solutions for this are Delayed Job (that Lars mentioned), and Resque:

John Bachir
  • 22,495
  • 29
  • 154
  • 227
2

How about using something like Delayed Job?

Lars Haugseth
  • 14,721
  • 2
  • 45
  • 49
1

I could be wrong, but I think code execution continues after a render, unless you put a return. This is why you get an error if you try to render twice..

NotDan
  • 31,709
  • 36
  • 116
  • 156
  • It sure does, however the response is not actually sent until after the method returns, which probably defeats the usefulness of the point of postponing doing something only after having sent the response to the requester or in OP case he later specified that at least the return code should be sent, but even that is not sent before the method returns. – Timo Dec 09 '21 at 16:00
0

Are you rendering html? If so, maybe you can insert some javascript into the rendered page to make a new request to your controller and initiate the further action that you need to take.

CharlieMezak
  • 5,999
  • 1
  • 38
  • 54