Rails 5 ActiveJob Basics with Sidekiq

You can watch this tutorial as a screencast Rails 5 ActiveJob Basics with Sidekiq. Create a new background job.

rails g job newsletter

The generated job looks like this:

class NewsletterJob < ApplicationJob
  queue_as :default

  def perform(*args)

  end
end

We can implement the perform method:

puts "I am busy mailing newsletter."

Let's invoke the background job in rails console.

NewsletterJob.perform_later('some mailing text')
 Enqueued NewsletterJob (Job ID: 98d0efc9) to Async(default) with arguments: "some mailing text"
 Performing NewsletterJob from Async(default) with arguments: "some mailing text"
  => #<NewsletterJob:0x007f84 @arguments=["some mailing text"], @job_id="98d0efc9", @queue_name="default", @priority=nil, @provider_job_id="81e91bd">
 > I am busy mailing newsletter.
 Performed NewsletterJob from Async(default) in 6.93ms

We can use almost any background job processing library. Let's use sidekiq. Add the gem to Gemfile.

gem 'sidekiq'

Run bundle. In application.rb, specify the queue_adapter:

config.active_job.queue_adapter = :sidekiq

Generate a welcome mailer.

rails g mailer welcome

We can now use sidekiq to process sending welcome email.

WelcomeMailer.welcome_email('Bugs').deliver_later
 Enqueued ActionMailer::DeliveryJob (Job ID: b6d0484b) to Sidekiq(mailers) with arguments: "WelcomeMailer", "welcome_email", "deliver_now", "Bugs"
  => #<ActionMailer::DeliveryJob:0x007fc0 @arguments=["WelcomeMailer", "welcome_email", "deliver_now", "Bugs"], @job_id="b6d04d738", @queue_name="mailers", @priority=nil, @provider_job_id="6233205f5ae">

The argument to welcome_email must be serializable. Pass in integer, strings etc, otherwise you get the error:

ActiveJob::SerializationError: Unsupported argument type: User

Rails Screencast episode #14 shows how to view the enqued jobs using Sidekiq admin Rack app and how to use Sidekiq to process the jobs in the background.

Summary

In this article, you learned how to use ActiveJob in Rails 5 to process jobs in the background using sidekiq.


Related Articles

Watch this Article as Screencast

You can watch this as a screencast Rails 5 ActiveJob Basics with Sidekiq


Create your own user feedback survey