m26a
m26a

Reputation: 1413

How to perform a background job now?

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

Upvotes: 1

Views: 7667

Answers (1)

Prasad Surase
Prasad Surase

Reputation: 6574

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

Upvotes: 2

Related Questions