Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to put everything in app/workers for sidekiq?

I'm currently migrating from DJ to sidekiq and have a lot of plain old ruby objects that I would use like so:

Delayed::Job.enqueue(SomeService.new(id))

I thought I could just move SomeService into the app/workers folder and add include Sidekiq::Worker but it doesn't ever go into the sidekiq queue and just calls performs on the spot

class SomeService
  include Sidekiq::Worker

  def initialize(id)
    @some_instance = SomeClass.find_by(id: id)
  end 

  def perform
    @some_instance.do_something
  end
end

so instead I have to create a sidekiq worker to call the service

class SomeServiceWorker
  include Sidekiq::Worker

  def perform(id)
    SomeService.new(id).perform
  end
end

Is there a way to just use the SomeService, which contains an initialize method and perform method so I don't have to create a worker to call my service object?

like image 952
cvdv Avatar asked Oct 28 '25 06:10

cvdv


2 Answers

Only one mistake what you did, you forget to add "Worker" word in your class name in the first file!

class SomeServiceWorker
  include Sidekiq::Worker

  def initialize(id)
    @some_instance = SomeClass.find_by(id: id)
  end 

  def perform
    @some_instance.do_something
  end
end

And this code will run your worker

SomeServiceWorker.new(id).perform
like image 95
Andriy Kondzolko Avatar answered Oct 30 '25 18:10

Andriy Kondzolko


Sidekiq doesn't care much about where the files are and/or how they are named, as long as they include Sidekiq::Worker. The convention though, is to put all the workers in the app/workers directory and to name them as MyWorker.

You can then call them as:

MyWorker.perform_async params
like image 44
Aldo Ziflaj Avatar answered Oct 30 '25 19:10

Aldo Ziflaj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!