beanserver
beanserver

Reputation: 652

Making a non blocking HTTP request in a Rails app

Is anyone aware of a way to make outgoing non blocking HTTP requests from within Rails? I will need the response body eventually and am trying to avoid bringing up new frameworks to keep things simple.

Thanks

Upvotes: 7

Views: 2154

Answers (3)

Christopher G
Christopher G

Reputation: 499

This is not non-blocking, but you can set a very low read_timeout. Also catch the resulting timeout error, which itself is a small perf penalty:

request = Net::HTTP::Get.new(url)
http = Net::HTTP.new(url.host, url.port)

http.read_timeout = 1

begin
  http.request(request)
rescue Timeout::Error => e
end

I don't know of a basic rails mechanism that will both make a non-blocking call and receive the response. Rails is very much tied to the request/response cycle, so usually the basic controller execution path will have ended before the HTTP call returns.

Upvotes: -1

luisiniguezh
luisiniguezh

Reputation: 89

You can do something like this:

def async_post
  Thread.new do
    uri = URI('https://somewhere.com/do_something')
    response = Net::HTTP.post_form(uri, 'param1' => '1', 'param2' => '2')
    # do something with the response
  end
  # Execution continues before the response is received
end

Upvotes: 0

Jordan Running
Jordan Running

Reputation: 106077

You're looking for "background jobs" or "background workers." There are a variety of gems for this. This blog post has a good overview of what's out there. delayed_job is very popular right now.

Upvotes: -2

Related Questions