Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hook Before All Delayed Jobs

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.)

like image 567
Brian Glick Avatar asked Aug 23 '11 19:08

Brian Glick


1 Answers

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]
like image 190
Shyam Habarakada Avatar answered Oct 29 '22 21:10

Shyam Habarakada