trying to understand the delayed_job in Rails, I want to update all PIN which already expired in my gallery
class UpdatePinJob < ApplicationJob
queue_as :default
def perform(gallery)
gallery.where('DATE(expired_pin) > ?', Date.today).update_all('pin = ?', 'new_pin_here')
end
end
is that the correct way to use the job? and how do I call it then in my controller? I hope my question makes sense, why I use a queue for this case because I was thinking how if my galleries have thousands, and I want to update all, that was I was thinking to use delayed_job might help for this to scale it :) if something wrong on my question sorry, I am here trying to understanding
You are on the right track. I would advise to follow the instructions here: ActiveJobsBasics
To call it in your controller you should do this:
# Enqueue a job to be performed as soon as the queuing system is free.
UpdatePinJob.perform_later(gallery)
# Enqueue a job to be performed 1 week from now.
UpdatePinJob.set(wait: 1.week).perform_later(gallery)
One important thing that you should aware of is about actually executing the job. According to ActiveJob:
For enqueuing and executing jobs in production you need to set up a queuing backend, that is to say you need to decide for a 3rd-party queuing library that Rails should use. Rails itself only provides an in-process queuing system, which only keeps the jobs in RAM. If the process crashes or the machine is reset, then all outstanding jobs are lost with the default async backend. This may be fine for smaller apps or non-critical jobs, but most production apps will need to pick a persistent backend.
I would go with Sidekiq
Don't forget to do this:
# config/application.rb
module YourApp
class Application < Rails::Application
...
config.active_job.queue_adapter = :sidekiq
...
end
end
EDIT: If you are interested in how to schedule, that depends on what technology you are using. If you are deploying with Heroku, you could use Heroku Scheduler. If you are deploying in Digital Ocean, you could use Cron Jobs.