问题
I want to execute this on background
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
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
回答1:
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
refer http://edgeguides.rubyonrails.org/active_job_basics.html#enqueue-the-job
来源:https://stackoverflow.com/questions/43736602/how-to-perform-a-background-job-now