Sidekiq Gem for background jobs in Rails

If you working with lots of records and if it is taking lot of time for its operation like importing or exporting thousands of records or syncing more records, it is better to add it to background job.

Sidekiq is the gem that can be used for this purpose. Sidekiq uses multiple threads. The default thread in sidekiq is “Default”.

*
For sidekiq, we need to install redis server.

“sudo apt-get install redis” install and start the redis server for ur console.

* Add the sidekiq gem and run bundle install.

gem 'sidekiq'

* We need to generate the worker class under app/workers directory and the files inside the app/workers directory will be auto loaded.
Ex: /app/workers/test_worker.rb

class TestWorker
       include Sidekiq::Worker
       def perform
       end
    end

we need to include Sidekiq::Worker and perform method. Perform method inside the worker will be called automatically and the code which need to be executed background is written here.

We can call this worker class for controller method like this,

TestWorker.perform_async (if u want to pass the arguments you can pass here).
* Next we need to start sidekiq server by

bundle exec sidekiq

* If a job fails due to an error Sidekiq will retry that job. We can avoid the retry by giving sidekiq options.

sidekiq_options retry: false


*
In sidekiq we can schedule tha job after some time. For this instead of perform_async we will use perform_in.
Ex: PygmentsWorker.perform_in(1.hour, @snippet.id)

* We can prioritize the queue in sidekiq for example if we have multiple worker in our application and if we want specific worker to be processed first, we will assign the worker to the specific queue.
EX: sidekiq_options queue: “high”

* we can process the queue by running the sidekiq server with -q option.
bundle exec sidekiq -q high,5 default,1

RailsCarma has been offering ROR Development services for over past 8 years. Our developers are well versed with executing all kind of ruby on rails application development projects and enhancing the features of your existing Rails applications. Contact us to know more about our development skills and the projects we have worked on.