Ruby on Rails - Background Jobs
Introduction
Background jobs in Rails allow you to perform tasks asynchronously, improving the performance and responsiveness of your application. Rails provides a built-in framework called Active Job that helps you manage background jobs with various back-end systems. This guide will cover how to use background jobs in Rails with Active Job.
Key Points:
- Background jobs perform tasks asynchronously, improving performance.
- Active Job is Rails' built-in framework for managing background jobs.
- This guide covers how to create and manage background jobs in Rails using Active Job.
Setting Up Active Job
Active Job supports various back-end systems, such as Sidekiq, Resque, Delayed Job, and more. Here is an example of setting up Active Job with Sidekiq:
# Gemfile
gem 'sidekiq'
# config/application.rb
module MyApp
class Application < Rails::Application
config.active_job.queue_adapter = :sidekiq
end
end
# config/routes.rb
require 'sidekiq/web'
mount Sidekiq::Web => '/sidekiq'
In this example, the Sidekiq gem is added, and Active Job is configured to use Sidekiq as the queue adapter.
Creating a Job
To create a background job, use the Rails generator:
# Generate a new job named ExampleJob
rails generate job ExampleJob
# app/jobs/example_job.rb
class ExampleJob < ApplicationJob
queue_as :default
def perform(*args)
# Do something later
puts "Performing background job with arguments: #{args.inspect}"
end
end
In this example, a new job named ExampleJob
is created with a perform
method that will be executed in the background.
Enqueuing Jobs
You can enqueue jobs to be performed in the background using the perform_later
method. Here is an example:
# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def create
@article = Article.new(article_params)
if @article.save
ExampleJob.perform_later(@article.id)
redirect_to @article, notice: 'Article was successfully created.'
else
render :new
end
end
private
def article_params
params.require(:article).permit(:title, :body)
end
end
In this example, the ExampleJob
is enqueued to run in the background after an article is successfully created.
Scheduling Jobs
You can schedule jobs to run at a specific time using the set
method with perform_later
. Here is an example:
# Schedule a job to run 1 hour from now
ExampleJob.set(wait: 1.hour).perform_later(article.id)
In this example, the ExampleJob
is scheduled to run 1 hour after it is enqueued.
Handling Job Errors
You can handle errors in your jobs by rescuing exceptions within the perform
method. Here is an example:
# app/jobs/example_job.rb
class ExampleJob < ApplicationJob
queue_as :default
def perform(*args)
begin
# Do something that might fail
risky_operation
rescue StandardError => e
Rails.logger.error "Failed to perform job: #{e.message}"
end
end
private
def risky_operation
# Example operation that might raise an exception
raise "An error occurred"
end
end
In this example, any errors raised during the execution of the risky_operation
method are rescued and logged.
Job Callbacks
Active Job provides callbacks that allow you to run code at specific points in a job's lifecycle. Here is an example:
# app/jobs/example_job.rb
class ExampleJob < ApplicationJob
queue_as :default
before_perform do |job|
Rails.logger.info "About to perform job: #{job.arguments.inspect}"
end
after_perform do |job|
Rails.logger.info "Finished performing job: #{job.arguments.inspect}"
end
def perform(*args)
# Do something
puts "Performing job with arguments: #{args.inspect}"
end
end
In this example, callbacks are used to log messages before and after the job is performed.
Monitoring and Managing Jobs
You can monitor and manage your background jobs using the Sidekiq web UI or other tools provided by the job queue system you are using. Here is an example of mounting the Sidekiq web UI:
# config/routes.rb
require 'sidekiq/web'
mount Sidekiq::Web => '/sidekiq'
In this example, the Sidekiq web UI is accessible at /sidekiq
, where you can monitor and manage your jobs.
Conclusion
Background jobs in Rails, powered by Active Job, provide a powerful way to perform tasks asynchronously, improving the performance and responsiveness of your application. By understanding how to set up, create, enqueue, schedule, and manage background jobs, you can leverage this feature to handle time-consuming tasks efficiently.