delayed_job_active_record icon indicating copy to clipboard operation
delayed_job_active_record copied to clipboard

A way to get the job ID inside a worker?

Open LucasCioffi opened this issue 3 years ago • 2 comments

Hi All,

I noticed that Sidekiq has a way to get the job ID from within a worker.

Is there something similar with DJ?

class MyWorker
  def perform(params)
    puts "starting #{self.job_id}"
    # work gets done
    puts "finishing #{self.job_id}"
  end
end

The goal is to be able to see if a worker finishes. We're on Heroku and I think we are having some zombie "dynos" (servers) that get disconnected from our app before finishing their work.

Thank you!

LucasCioffi avatar Mar 01 '21 03:03 LucasCioffi

Perhaps a bit late for your use case, but you might try something like this to tag all your logs with the worker PID & job id:

module Delayed
  module Plugins
    class TaggedLogging < Delayed::Plugin
      Delayed::Worker.logger = Rails.logger

      callbacks do |lifecycle|
        lifecycle.around(:execute) do |worker, *args, &block|
          Rails.logger.tagged "Worker:#{$$}" do
            block.call(worker, *args)
          end
        end

        lifecycle.around(:invoke_job) do |job, *args, &block|
          Rails.logger.tagged "Job:#{job.id}" do
            block.call(job, *args)
          end
        end
      end
    end
  end
end
Delayed::Worker.plugins << Delayed::Plugins::TaggedLogging

jdelStrother avatar Dec 21 '21 14:12 jdelStrother

Simpler method: Put this in an initializer

module ActiveJob
  module QueueAdapters
    class DelayedJobAdapter
      class JobWrapper
        def before(job)
          job_data["provider_job_id"] = job.id
        end
      end
    end
  end
end

Then you can access it the way it was meant to be accessed, through provider_job_id inside your job

hrdwdmrbl avatar May 31 '24 17:05 hrdwdmrbl

Thank you very much, @hrdwdmrbl and @jdelStrother.

LucasCioffi avatar Sep 20 '24 13:09 LucasCioffi