Red Red - 1 year ago 60
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 Source

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

 def self.refresh_thumbnails
   // some code


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

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"

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