rails sidekiq / active job

本稿について

本稿はサイト運営者が学んだことなどを記したメモの内容です。
全てが正確な情報とは限りません。ご注意ください。また修正するべき点は適時修正していきます
Redisを利用するので、Redisを入れておくこと。

gemを入れる
gem 'sidekiq'

configファイルを作成する
$ atom config/initializers/sidekiq.rb

configファイルの設定
Rails.application.config.active_job.queue_adapter = :sidekiq


if Rails.env.production?
  Sidekiq.configure_server do |config|
    config.redis = { url: ENV['REDIS_URL'] }
  end


  Sidekiq.configure_client do |config|
    config.redis = { url: ENV['REDIS_URL'] }
  end
end

workerの起動数の設定
config/sidekiq.yml
:concurrency: 10
:logfile: ./log/sidekiq.log
:queues:
  - [init, 6]
  - [renaissance, 5]
  - [mail, 4]
  - [push, 3]
  - [recommend, 2]
  - [admin, 1]

queuesは、キューの入るkeyを指定できる。
配列の2つ目に入っている要素は、worker(job)の実行優先度

workerを置くディレクトリを作る
$ mkdir app/workers

workerを作成する
app/workers/firebase_worker.rb
class FirebaseWorker
  include Sidekiq::Worker
  sidekiq_options queue: :init


  def perform(id)
    @user = User.find(id)
    @user.init_store_data
  end
end

呼び出し
HogeWorker.perform_async user.id

時間差実行
HogeWorker.perform_at(5.hours.from_now)

active jobを使う場合

以下の設定が必要
config/application.rb
config.active_job.queue_adapter = :sidekiq

$ bundle exec rails g job hoge_job
      invoke  rspec
      create    spec/jobs/hoge_job_job_spec.rb
      create  app/jobs/hoge_job_job.rb


sidekiqの起動
$ bundle exec sidekiq

$ bundle exec sidekiq -C config/sidekiq.yml

時間差(時間指定して実行) 

- すぐに実行
HogeJob.perform_now object.id
- 1分後に実行
HogeJob.set(wait: 1.minutes).perform_later

- 時間を指定して実行
HogeJob.set(wait_until: Time.new(2020,6,21, 12,0,0).perform_later

localのredisで起動するときはこのURLを使う
REDIS_URL: 'redis://localhost:6379'

実行数の確認
Sidekiq::Stats.new.processed

ダッシュボードの確認
config/routes.rb
require 'sidekiq/web’
mount Sidekiq::Web => '/sidekiq'

activejobのテスト
spec/rails_helper.rb
config.include ActiveJob::TestHelper

expect(HogeJob).to have_been_enqueued

時間指定の確認
expect(HogeJob).to have_been_enqueued.at(start_at)


sidekiqの予約されているworkerの削除
    ss = Sidekiq::ScheduledSet.new # スケジュールされたジョブの一覧を取得
    sidekiq_job = ss.find { |job| job.args[0]['job_id'] == self.job_id}
    sidekiq_job.delete if sidekiq_job.present?_



Herokuで使う場合にはProcfileを記述してpushする
Procfile
web: bin/rails server -p $PORT -e $RAILS_ENV
worker: bundle exec sidekiq -C config/sidekiq.yml
[参考]



※ active jobのリトライについては別途調べる

[参考]
Back