How to perform a background job now?

拥有回忆 提交于 2019-12-08 04:07:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!