Is it possible to have a method run before ALL delayed_job tasks?
Basically, we're trying to make sure that every server that is running delayed_job has the latest instance of our code, so we want to run a method that checks this before every job is run.
(We already have the "check" method and use it elsewhere. The question is only about how to call it from delayed_job.)
There is an official way to do this now, via plugins. This blog post clearly describes how to do this, with examples http://www.salsify.com/blog/delayed-jobs-callbacks-and-hooks-in-rails (some events described in this article maybe outdated. see below for updated list based on lated DJ sources)
Essentially, you implement an initializer that sets up a delayed_job plugin like below:
# config/initializers/delayed_job_my_delayed_job_plugin.rb
module Delayed
  module Plugins
    class MyDelayedJobPlugin < Plugin
      callbacks do |lifecycle|
        # see below for list of lifecycle events
        lifecycle.after(:invoke_job) do |job|
          # do something here
        end
      end
    end
  end
end
Delayed::Worker.plugins << Delayed::Plugins::MyDelayedJobPlugin
You will have access to the following lifecycle events, and applicable arguments:
  :enqueue    => [:job],
  :execute    => [:worker],
  :loop       => [:worker],
  :perform    => [:worker, :job],
  :error      => [:worker, :job],
  :failure    => [:worker, :job],
  :invoke_job => [:job]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With