5

I have a webservice that processes user submitted data. The user doesn't need to receive a response based on that data, he just needs to submit it. However, I do need to process that data. Currently the processing takes place directly as a response to the post action, and after the processing, it return a statuscode. This normally takes 0.5s - 2s, but sometimes much longer, when a user submits a lot of data.

Is it possible in Rails to spawn a new thread for processing that data, while returning the status code (and thus finishing the request for the user)?

4

3 回答 3

4

Resque, Delayed Job, or Sidekiq should suit your needs.

You can find links to these three, and a couple more here: https://www.ruby-toolbox.com/categories/Background_Jobs

于 2012-12-15T00:15:28.217 回答
2

I think you can process data in background, using something like resque.

于 2012-12-14T23:34:44.377 回答
2

You can also use fork - Its not an elegant solution but it gets the job done and introduces no extra moving parts. To do that fork over the entire rails app ( pretty messy but the rails app serving the request will respond immediately ) and have the process detached:

class SomeController < ApplicationController
  def heavy_lifting
    process = fork do
      # calculate PI or process input
      # ...
      # sends the kill signal to current Process, which is the Rails App actually calculating PI
      Process.kill("HUP") 
    end
    Process.detach(process)
    # respond here
  end
end

Keep in mind
Although your processing/job might only need a few megs of memory to run, fork allocates as much memory as the parent process does. Here is a good summary of what fork generally does.

Update - Same thing with threads

class SomeController < ApplicationController
  def heavy_lifting
    Thread.new do
      # calculate PI or process input
      # ...
      Thread.kill
    end
    # respond here
  end
end
于 2012-12-15T13:48:40.833 回答