Red Red - 6 months ago 18
Ruby Question

Updating models periodically (intervals of time) in Rails

I have a rails app that is essentially running a game. I need to "recharge" certain attributes of records in my database after a certain amount of time (let's say, x seconds). What would the best way to do this be? Do I need to use a gem?

I am using rails 4.2.6, ruby 2.3.0, and active record for my ORM.

Answer

In the models you want to "refresh", you can setup static methods :

# app/models/product.rb

class Product < ActiveRecord::Base
 // some code

 def self.refresh_stocks
   // some code
 end

 def self.refresh_thumbnails
   // some code
 end

end

Then, I suggest you to define some custom rake tasks:

# lib/tasks/myapp.rake
namespace :myapp do
  namespace :products do
    desc 'Refresh products'
    task refresh: :environment do
      Product.refresh_stocks
      Product.refresh_thumbnails
    end
  end
end

Then, you can use the whenever gem to setup your scheduling in your cron tab thanks to a nice dsl:

# config.schedule.rb
every 1.hour do
  rake "myapp:products:refresh"
end

A big win is when you use capistrano to deploy your app: In that case use the whenever capistrano integration to automatically refresh you cron tab at each deployment.

Happy scheduling