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

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

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'

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

class ApplicationJob < ActiveJob::Base
  before_perform do |job|

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

Software Compatibility Best Practices

I spoke to some of the most talented and experienced software developers. I have created a guide that is filled with valuable insights and actionable ideas to boost developer productivity.

You will gain a better understanding of what's working well for other developers and how they address the software compatibility problems.

Get the Guide Now