Share This Article
Sidekiq is a full-featured background job processor that supports scheduled jobs, retries, and failures. As a result, It has a simple and efficient API that makes it easy to use in any ruby project.
The main feature of Sidekiq is its ability to process jobs concurrently. So, The action means that Sidekiq can process multiple jobs at the same time, which can make your Ruby code run faster.
How Does Sidekiq Work?
Sidekiq works by processing jobs concurrently. When you enqueue a job, Sidekiq will process it in the background while your Ruby code continues to run.
This background approach differs from the standard Ruby way of processing jobs: to process them once and block the rest of the code until we finish de job.
In addition, Sidekiq has features that make concurrent programming more accessible, such as automatic retries for failed jobs and rate limiting.
Getting Started
To get started using sidekiq, first, you need to add the sidekiq gem to your Gemfile:
gem 'sidekiq'
Then run bundle install
to install the gem.
Creating a Job
A sidekiq job is just a regular ruby class defined in the app/workers
directory.
For example, let’s say you want to create a job that sends an email.
You can create a ruby class like this:
class EmailWorker
def perform(user_id)
user = User.find(user_id)
UserMailer.welcome_email(user).deliver
end
end
Notice that the perform
the method is required; this is where you will define the log to process.
Queueing a Job
Once you have defined a job, you can queue it using the perform_async
method.
EmailWorker.perform_async(current_user.id)
The perform_async
the method will return immediately, meaning your web request will not be blocked.
A Sidekiq worker will process the job in the background.
Running Sidekiq
To run sidekiq, you need to start the sidekiq server using the sidekiq
command: bundle exec sidekiq
Scheduling Jobs with Sidekiq
Also, the Sidekiq also supports scheduling jobs to run in the future.
To schedule a background job, you can use the perform_in
method.
EmailWorker.perform_in(2.days, current_user.id)
You can also schedule a job to run at a specific time using the perform_at
method.
EmailWorker.perform_at(2.days.from_now, current_user.id)
Conclusion
This article taught you how to use sidekiq to process background jobs in your ruby applications.
You’ve also learned how to schedule jobs to run in the future.
If you’re interested in learning more about sidekiq, I recommend reading the sidekiq wiki.