3

Inside the perform method, I want to know what is the ID of the current job.

For instance, the enqueue, success, failure and error methods provide the job parameter:

def enqueue(job)
  puts job.id
end

Is it possible?

dmferrari
  • 149
  • 12

2 Answers2

1

I assume you are using sidekiq as a backend. In that case you may do the following:

def perform(*args)
  logger.info self.job_id
  # Do something later
end

Here is the log output

[ActiveJob] [RequestHandlerJob] [e9923650-cd02-40d1-937d-859852e92c61] e9923650-cd02-40d1-937d-859852e92c61

UPDATE

Sorry, missed that.

I found solution in that SO post

# config/initializers/delayed_job.rb
Delayed::Worker.logger = Logger.new(File.join(Rails.root, 'log', 'dj.log'))


class RequestHandlerJob < ActiveJob::Base
  queue_as :default

  def perform(user_id)
    u = User.find(user_id)
    Delayed::Worker.logger.info self.job_id
    # Do something later
  end
end


[retgoat@iMac-Roman ~/workspace/tapp/log]$ tail -f dj.log
I, [2016-06-24T07:58:32.329471 #23874]  INFO -- : 2016-06-24T07:58:32+0600: [Worker(host:iMac-Roman.local pid:23874)] Starting job worker
I, [2016-06-24T07:58:42.404522 #23874]  INFO -- : 2016-06-24T07:58:42+0600: [Worker(host:iMac-Roman.local pid:23874)] Job ActiveJob::QueueAdapters::DelayedJobAdapter::JobWrapper (id=7) RUNNING
I, [2016-06-24T07:58:42.448858 #23874]  INFO -- : 5f267272-8826-491d-b7d5-82a200e1a6b6
I, [2016-06-24T07:58:42.451204 #23874]  INFO -- : 2016-06-24T07:58:42+0600: [Worker(host:iMac-Roman.local pid:23874)] Job ActiveJob::QueueAdapters::DelayedJobAdapter::JobWrapper (id=7) COMPLETED after 0.0466
I, [2016-06-24T07:58:42.452007 #23874]  INFO -- : 2016-06-24T07:58:42+0600: [Worker(host:iMac-Roman.local pid:23874)] 1 jobs processed at 15.9642 j/s, 0 failed

Here is the job_id 5f267272-8826-491d-b7d5-82a200e1a6b6. Hope that will help.

Community
  • 1
  • 1
retgoat
  • 2,414
  • 1
  • 16
  • 21
  • I am not sure if it still applies as I am using Rails 4.1.8 and the Delayed Job gem from https://github.com/collectiveidea/delayed_job – dmferrari Jun 23 '16 at 18:58
  • I added delayed_job example. – retgoat Jun 24 '16 at 02:00
  • I guess I can't use ActiveJob::Base, as I am in rails 4.1.8 (not 4.2). Please correct me if I am wrong. – dmferrari Jun 27 '16 at 13:26
  • Could you please post your code we are talking about? In general there is the same approach for just delayed_job. You need to define logger in intializers and then you can find job id in it. – retgoat Jun 28 '16 at 06:21
0

What I did was in an initializer, you can monkey patch the JobWrapper class and use

module ActiveJob
  module QueueAdapters
    class DelayedJobAdapter
      class JobWrapper
        def perform(job)
        end
      end
    end
  end
end
hrdwdmrbl
  • 4,814
  • 2
  • 32
  • 41