0
0
RailsHow-ToBeginner · 3 min read

How to Use Background Jobs in Rails: Simple Guide

In Rails, you use Active Job to run background jobs by creating a job class and enqueuing it. You typically use a backend like Sidekiq to process these jobs asynchronously, keeping your app responsive.
📐

Syntax

To create a background job in Rails, define a job class that inherits from ApplicationJob. Use the perform method to specify the task. Enqueue the job with perform_later to run it asynchronously.

  • class MyJob < ApplicationJob: Defines the job class.
  • def perform(args): The method where the background task runs.
  • MyJob.perform_later(args): Enqueues the job to run in the background.
ruby
class MyJob < ApplicationJob
  queue_as :default

  def perform(name)
    puts "Hello, #{name}! This is a background job."
  end
end

# Enqueue the job
MyJob.perform_later('Rails Developer')
💻

Example

This example shows how to create a simple background job that prints a greeting message. It uses Sidekiq as the backend to process jobs asynchronously.

ruby
# Gemfile
# Add Sidekiq for background processing

gem 'sidekiq'

# Run bundle install

# config/application.rb
module YourAppName
  class Application < Rails::Application
    config.active_job.queue_adapter = :sidekiq
  end
end

# app/jobs/greeting_job.rb
class GreetingJob < ApplicationJob
  queue_as :default

  def perform(name)
    puts "Hello, #{name}! This runs in the background."
  end
end

# Enqueue the job somewhere in your app
GreetingJob.perform_later('Friend')
Output
Hello, Friend! This runs in the background.
⚠️

Common Pitfalls

Common mistakes when using background jobs in Rails include:

  • Not setting the queue_adapter, so jobs don't run.
  • Using perform_now instead of perform_later, which runs jobs immediately, blocking the main thread.
  • Forgetting to start the background job processor (e.g., Sidekiq server), so jobs stay queued but never run.
  • Not handling exceptions inside perform, causing jobs to fail silently.
ruby
## Wrong: runs job immediately, blocking
GreetingJob.perform_now('Friend')

## Right: runs job asynchronously
GreetingJob.perform_later('Friend')
📊

Quick Reference

Summary tips for using background jobs in Rails:

  • Use Active Job for a unified interface.
  • Choose a backend like Sidekiq for efficient processing.
  • Always enqueue jobs with perform_later.
  • Start your job processor with bundle exec sidekiq.
  • Handle errors inside perform to avoid silent failures.

Key Takeaways

Use Active Job with perform_later to run tasks in the background.
Set a queue adapter like Sidekiq for real asynchronous processing.
Never use perform_now for background jobs as it blocks the main thread.
Always start your background job processor to execute queued jobs.
Handle exceptions inside your job's perform method to avoid silent failures.