0
0
RailsHow-ToBeginner · 4 min read

How to Use Delayed Job in Rails for Background Processing

To use delayed_job in Rails, add the gem to your Gemfile, run the generator and migrations, then call delay on any method you want to run in the background. This lets Rails handle long tasks asynchronously without blocking user requests.
📐

Syntax

The basic syntax to run a method asynchronously with Delayed Job is to call delay on an object or class method. For example, object.delay.method_name(args) queues the method to run later.

Key parts:

  • delay: tells Rails to run the method in the background
  • method_name: the method you want to run later
  • args: any arguments the method needs
ruby
user.delay.send_welcome_email

# or for class methods
User.delay.cleanup_old_accounts
💻

Example

This example shows how to set up Delayed Job and use it to send a welcome email without blocking the web request.

ruby
## Gemfile
# Add delayed_job_active_record gem

gem 'delayed_job_active_record'

## Terminal commands
# Install gem and generate migration
bundle install
rails generate delayed_job:active_record
rails db:migrate

## app/models/user.rb
class User < ApplicationRecord
  def send_welcome_email
    # Simulate sending email
    puts "Sending welcome email to #{email}"
  end
end

## Usage in controller or console
user = User.first
user.delay.send_welcome_email
Output
Sending welcome email to user@example.com
⚠️

Common Pitfalls

Common mistakes when using Delayed Job include:

  • Not running the background worker process (bin/delayed_job start) so jobs never execute.
  • Calling methods that rely on request-specific data or session, which won't be available in background jobs.
  • Not handling exceptions inside delayed methods, causing silent failures.
  • Forgetting to migrate the database after installing the gem.
ruby
## Wrong: calling method without delay
user.send_welcome_email  # runs immediately, blocking request

## Right: call with delay
user.delay.send_welcome_email  # runs asynchronously
📊

Quick Reference

ActionCommand / Code
Add gemgem 'delayed_job_active_record'
Generate migrationrails generate delayed_job:active_record
Run migrationrails db:migrate
Start workerbin/delayed_job start
Run method in backgroundobject.delay.method_name(args)

Key Takeaways

Add and migrate delayed_job gem before using it in Rails.
Use object.delay.method to run tasks asynchronously.
Always start the delayed_job worker to process jobs.
Avoid using request-specific data inside delayed methods.
Handle errors inside background jobs to prevent silent failures.