def install
plugin = Class.new(Delayed::Plugin) do
require 'delayed_job'
callbacks do |lifecycle|
lifecycle.around(:invoke_job) do |job, *args, &block|
ScoutApm::Agent.instance.start_background_worker unless ScoutApm::Agent.instance.background_worker_running?
name = begin
case job.payload_object.class.to_s
when ACTIVE_JOB_KLASS
job.payload_object.job_data["job_class"]
when DJ_PERFORMABLE_METHOD
job.name
else
job.payload_object.class.to_s
end
rescue
job.name
end
queue = job.queue || "default"
req = ScoutApm::RequestManager.lookup
begin
latency = Time.now - [job.created_at, job.run_at].max
req.annotate_request(:queue_latency => latency)
rescue
end
queue_layer = ScoutApm::Layer.new('Queue', queue)
job_layer = ScoutApm::Layer.new('Job', name)
begin
req.start_layer(queue_layer)
started_queue = true
req.start_layer(job_layer)
started_job = true
block.call(job, *args)
rescue
req.error!
raise
ensure
req.stop_layer if started_job
req.stop_layer if started_queue
end
end
end
end
Delayed::Worker.plugins << plugin
end