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 ha estado ofreciendo ROR Development services durante más de 8 años. Nuestros desarrolladores están bien versados en la ejecución de todo tipo de Desarrollo de aplicaciones Ruby on Rails. proyectos y mejorando las características de sus aplicaciones Rails existentes. Contáctenos para saber más sobre nuestras habilidades de desarrollo y los proyectos en los que hemos trabajado.

Suscríbete para recibir las últimas actualizaciones

Artículos Relacionados

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

es_ESSpanish