jondot / sneakers

A fast background processing framework for Ruby and RabbitMQ
https://github.com/jondot/sneakers
MIT License
2.24k stars 333 forks source link

How to Inject code into worker initialization? #477

Open raymzag opened 1 year ago

raymzag commented 1 year ago

Is there a better way than this if I want to inject a third party api client into the worker process? I have tried before_fork and after_fork hooks, but not working in my use case, because the api client will spawn child process to update its own cache from remote api. If I put Client.new in the main sneaker thread (or before/after fork), the cache updates do not get propagated to worker MyWorker processes. So, I resorted to code below, which seems to be working. But I am wondering if there's better ways?

class MyWorker
  include Sneakers::Worker
  attr_reader :my_client

  def initialize(...)
    super(...)
    @my_client = Client.new(...)
  end

  from_queue 'myworker'

  def work(data)
    puts "executing at #{Time.now}"
    puts my_client.method()
    ack!
  end
end