11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Sidekiq で enqueue する queue を動的に指定する

Last updated at Posted at 2015-04-16

sidekiq で enqueue する queue を指定するには、通常は

class HardWorker
  include Sidekiq::Worker
  sidekiq_options queue: :event

  def perform(params)
  end
end

HardWorker.perform_async(params)

のようにクラスを1つ定義して、sidekiq_options で指定する。

これを、sidekiq_options ではなく、enqueue (perform_async) 時に動的に指定するにはどうするか。

やり方

Sidekiq::Worker.perform_async ではなく Sidekiq::Client.enqueue_to を使う。

Sidekiq::Client.enqueue_to(:my_queue, HardWorker, params)

どちらも最終的に行き着く所は同じ。

lib/sidekiq/client.rb#L146-L151 あたりに書いてある。

      # Example usage:
      #   Sidekiq::Client.enqueue_to(:queue_name, MyWorker, 'foo', 1, :bat => 'bar')
      #
      def enqueue_to(queue, klass, *args)
        klass.client_push('queue' => queue, 'class' => klass, 'args' => args)
      end

dequeue する方は

bundle exec sidekiq -q my_queue

のように sidekiq を起動するコマンドオプションで指定する

おわりに

いちいちクラス作らなくて良くなった。priority queue を使いたい時などに役立つ。

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?