现在如何执行后台工作? [英] How to perform a background job now?
问题描述
我想在后台执行此操作
Product.all.map { |product| product.save }
当我保存产品时,将调用回调函数以在表中创建新记录用产品成本
When I save the product will call a callback to create a new record in a table with the costs of products
我为此创建了一个作业,但是如果执行 perform_now
,则不会执行该作业后台和 perform_later
会执行很长时间。
I create a job for this, but if I execute perform_now
it is not executed on background and perform_later
executes long after.
我现在想在后台执行此操作。我不确定是否也可以在线程中执行此操作。
I want to execute this right now but in background. I'm not sure if I can just execute this in a thread too.
我正在使用延迟作业,这是作业
I am using Delayed Job, here is the job
class UpdateProductCostsJob < ApplicationJob
queue_as :default
def perform
Product.all.map { |product| product.save }
end
end
我想每次执行此模型已保存
And I want to execute every time this model is saved
class CostComposition < ApplicationRecord
before_save :update_product_costs
private
def update_product_costs
UpdateProductCostsJob.perform_now
end
end
推荐答案
假设您正在使用rails 5,则可以创建一个高优先级队列并创建该队列下的工作。如果只有一个队列,则可以将作业添加到队列中,并指定要处理该作业的时间。
Assuming that you are using rails 5, you can create a high priority queue and create the job under that queue. If you have only one queue, you can add the job to the queue as well as specify the time when you want to process that job.
UpdateProductCostJob.set(wait_until: Time.now + 5.minutes).perform_later
参考< a href = http://edgeguides.rubyonrails.org/active_job_basics.html#enqueue-the-job rel = nofollow noreferrer> http://edgeguides.rubyonrails.org/active_job_basics.html#enqueue-the-job
这篇关于现在如何执行后台工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!