2

I am working on a ruby&rails application, where the requirement is following: On receiving the HTTP request, the controller has to store the data in the database and return success to the end user. At this point, I want a background thread to wake up and perform operations on the added data. I am using the WEBRick server in the development mode. How to achieve this functionality?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • There are many ways to do this. Check out your options at https://www.ruby-toolbox.com/categories/Background_Jobs – Brad Werth Apr 16 '14 at 16:44

1 Answers1

1

Since you're looking for background processing libraries lot's of people recommend resque and sidekiq. You can look at this sitepoint tutorial for a good article comparing Delayed Job with the other two (I don't know that one so shan't comment on it here) and you can see a good comparison of these two in this stack overflow answer.

One of the main things to think about is whether your code that you want to run in a background process is theadsafe? if it's not stick to resque (I think it's simpler anyway, matter of opinion) because sidekiq runs parallel jobs (I'm sure you can choose to not do this).

Sample code: Redis (From docs):

To define some work, make a job. Jobs need a work method:

class ImageConversionJob
  def work
    # convert some kind of image here
  end
end

Next, we need to procrastinate! Let's put your job on the queue:

resque = Resque.new
resque << ImageConversionJob.new

Neat! This unit of work will be stored in Redis. We can spin up a worker to grab some work off of the queue and do the work:

bin/resque work

Sidekiq (from linked sitepoint article):

class PrintWorker
  include Sidekiq::Worker

  def perform(str)
    puts str
  end
end

Once again, we have to queue up a job somewhere (we’ll do it in the index controller):

class IndexController < ApplicationController
  def index
    PrintWorker.perform_async(params[:to_print])
  end
end

Finally, we have to get the Sidekiq process(es) fired up. Type this into your shell in the root directory of your Rails app:

bundle exec sidekiq

This is just a quick rundown and enough syntax to get a flavour of the answers. For more detail see the linked articles.

Community
  • 1
  • 1
Mike H-R
  • 7,726
  • 5
  • 43
  • 65