Rails - 延迟完成作业

时间:2012-06-22 07:41:58

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

我有一个基于ruby on rails的Web应用程序,它使用this延迟作业gem。

我有一个触发延迟作业的功能,这又会触发其他几个延迟的作业。有没有办法,巢案是一个事件,可以表明所有与父母有关的工作已经完成?或者,当我尝试检索docuemnts时,我是否只需要处理可用的任何数据?

示例:

def create_vegetable
#..... creates some vegetable
end

def create_vegetable_asynchronously id
  Farm.delay(priority: 30, owner: User.where("authentication.auth_token" => token).first, class_name: "Farm", job_name:create "create_vegetable_asynchronously").create_vegetable(id)
end

def create_farm_asynchronously data
  data.each do |vegetable|
    create_vegetable_asynchronously vegetable.id
  end
end

handle_asynchronously :create_farm_asynchoronously

1 个答案:

答案 0 :(得分:3)

可能有点矫枉过正,但您可以按层次结构明确地组织您的作业,并在挂钩之前使用父作业ID传递给子任务。 类似的东西:

class Job < Delayed::Job
  belongs_to :parent, class: 'Job' #also add db column for parent_id
end

class CreateVegetable 

   def initialize(id)
     @id = id
   end

   def perform
     Farm.create_vegetable(id)
   end

end


class CreateFarm 
   def initialize(vegetable_ids,owner_id)
     @vegetable_ids = vegetable_ids
     @owner_id = owner_id
   end

   def before(job)
     @job_id = job.id
   end

   def perform
     @vegetable_ids.each { |id| Job.enqueue CreateVegetable.new(id), priority: 30, owner_id = @owner_id, :parent_id = @job_id }
   end

end

然后,当您启动create farm时,不知何故还记得作业ID。

def create_farm_asynchronously data
   owner_id = User.where("authentications.auth_token" => token).first.id
   @parent = Job.enqueue CreateFarm.new(data.map(&:id), owner_id)
end

然后您可以通过以下方式检查子作业:

Job.where(parent_id: @parent.id)