Sidekiq By Example
What is the best way of handling background jobs in Rails, (maybe) using sidekiq.
Let’s take step by step look into creating a Rails App and making a request for Background job using sidekiq
Note: The repository of this project.
Create new Rails Project
We will create a new rails project named
Add sidekiq gem
Gemfile add gem ‘sidekiq’
Now run command
bundle install. This will install gem sidekiq in our project.
➜ sidekiq-example: bundle install
Let’s create a model named
Team for reference with fields
Also add this in
➜ sidekiq-example: rails db:create && rails db:migrate && rails db:seed
It will create new database
sidekiq_example_development for our application and create a table called
teams in this database.
Running seed data will insert sample 5 records in it.
Generate a controller
Create a controller for our actions under namespace
Let’s add routes for our actions. Add this in
Add Sidekiq worker
Now let’s work on Sidekiq part. To perform sidekiq jobs, add worker in
app/workers. For our demo application
BuyTimeWorker. And add method named perform in it. When a call to
BuyTimeWorker made, it will be a
asynchronous call to this method
The logic for background job will be in this method
perform. To keep it simple for now, will just add sleep timer
It simply sleeps for number of milliseconds passed to it. This job will run asynchronously when called.
Let’s modify teams controller to make a call to this background job
You can see action
show is making call to
BuyTimeWorker. What it means is when a url of kind
is hit, the controller action
show will get called and background job
BuyTimeWorker will be triggered. The action
will not wait for job
BuyTimeWorker to complete though it is called from within its definition. This job will be
executed asynchronously with method
- Start rails server
- Start Redis
- Start Sidekiq
If you hit URL will found out something like this in sidekiq server log
Well this is very simple example of running background job in rails. You can write complex logic in Sidekiq workers. You can add multiple workers.