Search code examples
ruby-on-railsrubydelayed-job

Call specific method when delayed_job failed


I'm looking for a way to do a specific treatment when a delayed_job failed on my rails app. I don't know if it's possible, and how I can configure DelayedJob for that.
I saw that I can add the error method for one specific job, but I want something similar for all jobs.

Any ideas?


Solution

  • I would suggest you to use a Delayed::Plugin and follow this tutorial:
    http://www.salsify.com/blog/engineering/delayed-jobs-callbacks-and-hooks-in-rails

    You will be able to trigger an event for any job failure across your app.
    For instance:

    require 'airbrake'
    require 'delayed_job'
    
    class AirbrakePlugin < Delayed::Plugin
    
      callbacks do |lifecycle|
        lifecycle.around(:invoke_job) do |job, *args, &block|
          begin
            # Forward the call to the next callback in the callback chain
            block.call(job, *args)
          rescue Exception => error
            ::Airbrake.notify_or_ignore(
                :error_class   => error.class.name,
                :error_message => "#{error.class.name}: #{error.message}",
                :backtrace => error.backtrace,
                :parameters    => {
                    :failed_job => job.inspect
                }
            )
            # Make sure we propagate the failure!
            raise error
          end
        end
      end