Share This Article
Sidekiq is a Ruby gem for background processing. It’s one of the most popular background job processing tools available.
In this article, you will learn how to install Sidekiq in your Ruby project & how to monitor your jobs.
Installing Sidekiq
If you want to use sidekiq in your Ruby project, you need to add it to your Gemfile.
gem "sidekiq"
You also need to add the Sidekiq middleware to your application.
# config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
config.server_middleware do |chain|
chain.add Sidekiq::Middleware::Server::RetryJobs
end
end
Sidekiq.configure_client do |config|
config.client_middleware do |chain|
chain.add Sidekiq::Middleware::Client::RetryJobs
end
end
Configuring Sidekiq
You might want to configure Sidekiq to suit your needs.
For example, you can configure the log file, the queue, the Redis server, etc.
Here’s an example Sidekiq configuration file:
# config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
config.redis = { url: 'redis://localhost:6379/0' }
config.server_middleware do |chain|
chain.add Sidekiq::Middleware::Server::RetryJobs
end
end
Sidekiq.configure_client do |config|
config.redis = { url: 'redis://localhost:6379/0' }
config.client_middleware do |chain|
chain.add Sidekiq::Middleware::Client::RetryJobs
end
end
Defining Sidekiq Jobs
Sidekiq jobs are just Ruby classes that respond to the perform
method.
Here’s a simple example:
class HelloWorldJob
def perform
puts "Hello, world!"
end
end
You can also define jobs that take arguments.
Here’s an example:
class GreetingJob
def perform(name)
puts "Hello, #{name}!"
end
end
And you can enqueue jobs using the perform_async
method.
Here’s an example:
GreetingJob.perform_async("John")
Note: The perform_async
method is defined by the Sidekiq::Worker
module.
Monitoring Sidekiq Jobs
Sidekiq ships with a Web UI that you can use to monitor & manage your jobs.
You can find the source code for the Web UI on Github.
It’s also possible to monitor your jobs using the Sidekiq::Stats
class.
Here’s an example:
# Get the total number of processed jobs
Sidekiq::Stats.new.processed
# Get the number of processed jobs in the last hour
Sidekiq::Stats.new.processed_in_last_hour
# Get the number of failed jobs in the last hour
Sidekiq::Stats.new.failed_in_last_hour
There are also other methods you can use, you can find the complete list on Github.
You can also monitor your Sidekiq jobs using a third-party tool like Airbrake.
Summary
In this article, you’ve learned how to install Sidekiq in a Ruby project, how to configure it, how to define jobs, & how to monitor them.
If you want to learn more about Sidekiq, you can check out the documentation.