Active job in Rails: Things You Need to Know ๐Ÿ’Ž

Ajithkumar P S - Jan 6 - - Dev Community

What is Active Job?

Active Job was first made available in Rails from 4.2. When you create a new rails app Active Job will be the default framework for creating, enqueuing and executing background jobs. These jobs can be everything from sending emails, putting images into S3 bucket like so on.

The Goal of Active Job:

By default all rails apps will have a job setup in place. We can then have other background job frameworks and other gems build on top of that, without having to worry about their API differences between them such as Sidekiq and Resque.

Note ๐Ÿ“—
An in-process thread pool is a way of running jobs concurrently within a single process, using multiple threads. Rails by default comes with an asynchronous queuing implementation that runs jobs with an in-process thread pool. This is well-suited for dev/test environments, since it doesnโ€™t need an external infrastructure, but itโ€™s not recommended for production, since it drops pending jobs on restart.

Creating a Job ๐Ÿš€:

Enough talking, Letโ€™s start doing. An example of an active job. In this example, I'm assuming you have a User model and UserMailer with a send_welcome_email method that sends the email. Let's say you want to create a background job that sends an โœ‰๏ธ email after new user creation. First, you need to generate a new job:

rails generate job send_welcome_email
Enter fullscreen mode Exit fullscreen mode

In app/jobs/send_email_job.rb file, define your job.

class SendWelcomeEmailJob < ApplicationJob
  queue_as :default

  def perform(user)
    UserMailer.welcome_email(user).deliver_later
  end
end

Enter fullscreen mode Exit fullscreen mode

When you use deliver_later, the email is not send at the moment, but rather is pushed in a job's queue.

Enqueuing a Job โžก๏ธ:

class User < ApplicationRecord
    after_create :send_welcome_email

    def send_welcome_email
        SendWelcomeEmailJob.perform_later(self)
    end
end
Enter fullscreen mode Exit fullscreen mode

If you use perform_later method, It will enqueue a job to be performed as soon as the queuing system is free.

Queuing Backends ๐Ÿ”™:

For enqueuing and executing jobs in production you need to set up a queuing backend, that is to say, you need to decide on a 3rd-party queuing library that Rails should use. Rails itself only provides an in-process queuing system, which only keeps the jobs in RAM. If the process crashes or the machine is reset, then all outstanding jobs are lost with the default async backend. This may be fine for smaller apps or non-critical jobs, but most production apps will need to pick a persistent backend(Sidekiq, Resque, Delayed Job, and others). For more info visit official guide: https://guides.rubyonrails.org/active_job_basics.html

Thanks for reading, Happy coding!!!

. . . . . . . . .