Ruby 从作业任务中引用延迟的作业id

Ruby 从作业任务中引用延迟的作业id,ruby,delayed-job,Ruby,Delayed Job,我有一个延迟的工作任务,它会吐出一个文件。我希望能够使用创建该文件的作业的ID作为该文件的前缀,以便以后方便地引用它 # Create a file that has the job id in the name... job_id = thing.delay.create_file # Now we'll use the job_id to search for the file... 这可能吗?延迟的\u作业使用一个表对作业进行排队,该表可以在中找到。该表将有一个默认id列,您可以查询该列

我有一个延迟的工作任务,它会吐出一个文件。我希望能够使用创建该文件的作业的ID作为该文件的前缀,以便以后方便地引用它

# Create a file that has the job id in the name...
job_id = thing.delay.create_file
# Now we'll use the job_id to search for the file...

这可能吗?

延迟的\u作业使用一个表对作业进行排队,该表可以在中找到。该表将有一个默认id列,您可以查询该列:

ActiveRecord::Base.connection.raw_connection.prepare("Select id FROM delayed_job where handler=?","YAML Encoded string representing the object doing work")

让我们从这里开始

class WriteFileJob
  attr_accessor :dj_id, :file_name

  def initialize(file_name)
    @file_name = file_name
  end

  def perform
    # do something with @dj_id; don't worry, we'll set it below
  end
end
现在,当您将作业排队时,您应该可以重新获得作业:

j = Delayed::Job.enqueue(WriteFileJob.new("foo.txt"))
接下来,加载已排队的对象,并使用刚返回的id对其进行更新:

object_to_update = YAML.load(j.handler)
object_to_update.dj_id = j.id
# update the handler
j.handler = object_to_update.to_yaml
j.save

请在create_file task中包含代码。DJ在处理完条目后会删除它们,那么作业ID对您有何用处?@muistooshort-失败的作业不会被删除谢谢,这会起作用,不过我希望不会涉及重新查询数据库。@Yarin:-)以防您担心作业执行太早(在分配@dj_id之前),如果@dj_id.nil?则可以引发异常
,以便作业稍后再次运行(或者可以在开始时指定run_)