Railsのバックグラウンドジョブ用のSidekiq Gem

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 が提供している ROR Development services 過去8年間以上。当社の開発者は、あらゆる種類の実行に精通しています。 Ruby on Rails アプリケーション開発 プロジェクトを構築し、既存の Rails アプリケーションの機能を強化します。当社の開発スキルやこれまでに取り組んできたプロジェクトについて詳しく知りたい場合は、お問い合わせください。

最新のアップデートを購読する

関連記事

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

jaJapanese