我有一个基于 ruby on Rails 的 Web 应用程序,它使用 this延迟工作 gem 。
我有一个函数可以触发延迟作业,而该函数又会触发其他几个延迟作业。有没有一种方法,嵌套案例是一个事件,可以表明与父级相关的所有作业都已完成?或者当我尝试检索文档时,我是否只需要处理可用的任何数据?
示例:
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
最佳答案
也许有点矫枉过正,但您可以明确地分层组织您的作业,并使用 before hook 将父作业 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
然后,当您启动创建农场时,请记住作业 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)
关于ruby-on-rails - Rails - 延迟作业完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11152078/