Rails 5.1 ActiveJob Basics

This article covers the basics of ActiveJob in Rails 5.1. The resque is used as the background job processor . To create a background job, we can use the rails generator:

rails generate job newsletter_subscriber

This creates the job in app/jobs directory. We can create a job that will run on a specific queue:

rails generate job newsletter_subscriber --queue subscriber

This will run the newsletter_subscriber job in the queue named subscriber. This generates the job:

class NewsletterSubscriberJob < ApplicationJob
  queue_as :default

  def perform(*subscriber)
    # Do something later
  end
end

We can enqueue a job like this:

NewsletterJob.perform_later subscriber_id

The perform_later will call perform method under the hood. Rails keeps the jobs in memory. In production, we need a queuing library that Rails should use. ActiveJob has built-in adapters for many popular queuing backends such as sidekiq, resque, delayed job and others. We can set the queing backend in application.rb like this:

# config/application.rb
module JDemo
  class Application < Rails::Application
    # Be sure to have the adapter's gem in your Gemfile
    # and follow the adapter's specific installation
    # and deployment instructions.
    config.active_job.queue_adapter = :resque
  end
end

The jobs run outside the request-response cycle of Rails. They run in parallel as a separate process of your Rails application process. So, we need to start the queuing service after the Rails app is started to make the background job processing to work. Refer resque library docs for instructions. To run the jobs in the default queue:

$ QUEUE=default rake resque:work

Add the resque gem and install it using bundler.

gem 'resque'
bundle

Do the following if you are going to the database in lot of background jobs:

class ApplicationJob < ActiveJob::Base
  before_perform do |job|
    ActiveRecord::Base.clear_active_connections!
  end
end

You can view the background job processing from the browser by running:

$ resque-web

in the terminal. You can run a background job in the rails console and see that it is in the pending queue in the admin UI. In lib/tasks/reque.rake, add this line:

require 'resque/tasks'

You can now process all the background jobs using resque in all queues by running the command:

QUEUE=* rake environment resque:work

If you see the admin UI, the pending job will go to processed state.


Related Articles

Watch this Article as Screencast

You can watch this as a screencast Rails 5.1 ActiveJob Basics


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.