0
0
Ruby on Railsframework~5 mins

Active Job framework in Ruby on Rails

Choose your learning style9 modes available
Introduction

Active Job helps you run tasks in the background so your app stays fast. It makes it easy to do things later without slowing down users.

Sending emails after a user signs up without making them wait
Processing image uploads or resizing photos after upload
Running slow database cleanup tasks at night
Sending notifications or messages without delay
Performing API calls to other services without blocking user actions
Syntax
Ruby on Rails
class MyJob < ApplicationJob
  queue_as :default

  def perform(*args)
    # Do the work here
  end
end
Define a job by creating a class that inherits from ApplicationJob.
Use the perform method to write the task you want to run in the background.
Examples
This job sends a welcome email to a user using the mailers queue.
Ruby on Rails
class EmailUserJob < ApplicationJob
  queue_as :mailers

  def perform(user)
    UserMailer.welcome_email(user).deliver_now
  end
end
This job deletes old records using a low priority queue.
Ruby on Rails
class CleanupJob < ApplicationJob
  queue_as :low_priority

  def perform
    OldRecord.where('created_at < ?', 1.month.ago).delete_all
  end
end
Enqueue the job to run later with arguments.
Ruby on Rails
MyJob.perform_later(arg1, arg2)
Sample Program

This job prints a greeting message with the given name. It runs in the background when enqueued.

Ruby on Rails
class GreetUserJob < ApplicationJob
  queue_as :default

  def perform(name)
    puts "Hello, #{name}!"
  end
end

# Enqueue the job
GreetUserJob.perform_later('Alice')
OutputSuccess
Important Notes

Active Job works with many background systems like Sidekiq, Resque, or Delayed Job.

Use perform_later to run jobs asynchronously and perform_now to run immediately.

Always keep jobs small and focused to avoid long delays.

Summary

Active Job lets you run tasks in the background easily.

Define jobs by subclassing ApplicationJob and writing a perform method.

Use perform_later to enqueue jobs without blocking your app.