Rails 4 - 延迟作业 - 是否可以在执行方法中知道作业ID?

时间:2016-06-21 19:39:48

标签: ruby-on-rails-4 delayed-job

perform方法中,我想知道当前作业的ID是什么。

例如,enqueuesuccessfailureerror方法提供job参数:

def enqueue(job)
  puts job.id
end

有可能吗?

1 个答案:

答案 0 :(得分:0)

我假设你使用sidekiq作为后端。在这种情况下,您可以执行以下操作:

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

这是日志输出

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

<强>更新

抱歉,错过了。

我在here

中找到了解决方案
# 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

这是job_id 5f267272-8826-491d-b7d5-82a200e1a6b6。希望这会有所帮助。