Skip to content

How To: Rails Background Jobs

Dotan J. Nahum edited this page Oct 12, 2013 · 4 revisions

Using Sneakers is simple with Rails too. You can get along fine with what you've seen so far, however since we're using Rails, we can adapt to be even more productive by hooking up some conventions.

Hopefully we'll create a sneakers-rails gem that sets this up for you, but until then here's how to set up manually.

Rails

As always, add sneakers to your Gemfile. In your Rakefile, add this:

require 'sneakers/tasks'

Which will pull useful tasks for you.

rake sneakers:run       # Start work (set $WORKERS=Klass1,Klass2)

Workers folder

Make rails aware of your worker folder. We'll set this in app/workers.

# config/application.rb
config.autoload_paths += %W(#{Rails.root}/app/workers)

Global configuration

Next, let's give you a place to configure global parameters for Sneakers; often this is all you'll do, or better, you won't need it and just use the default configuration.

Set up an initializer file, named after the sneakers gem.

# config/initializers/sneakers.rb
require 'sneakers'
Sneakers.configure(:runner_config_file => 'sneakers.conf.rb', :daemonize => true)

This sets up a sneakers.conf.rb file which will exist at the root of your Rails app. You'll only need this if you want to support auto-scaling or have special before/after forks hooks to set up.

Starting up

Next you need to export the worker classes you want to run, and invoke the Sneakers rake task:

WORKERS=WebScraper rake sneakers:run

That's all folks. With the sneakers-rails gem only the 'starting up' stage will be relevant. We're accepting pull requests :)