Search code examples
ruby-on-railsactiverecordrails-activejob

How do I change attributes of a model after a set time


I have a timer class in my application set to expire 24 hours after creation.

Is there a way to run expire_if_running 24 hours after creation date, or do I have to run a cron job every minute?

class Timer < ApplicationRecord
  enum status: {
    running: 1, # the default
    expired: 2 # timed out
    finished: 3 # completed
  }

  # if the Timer isn't finished, expire it
  def expire_if_running
    self.status = "expired" if self.running?
  end
end

Please provide sample code or a citation for your answer. I've never used ActiveJob before, and I have the faint feeling this is the sort of case that requires it.


Solution

  • I found a way to run this exact same scenario using delayed_job, which is better since it runs at a time in the future.

    A cronjob by the minute can be 59 seconds late in expiring the timer.
    A cronjob by the hour can be 59 minutes late in expiring the timer.

    Here's a tutorial from Twilio on how to make a reminder app.