在 Rails 中定期(时间间隔)更新模型

Updating models periodically (intervals of time) in Rails

我有一个 rails 应用程序,它本质上是 运行 一款游戏。在一定时间(比方说,x 秒)后,我需要 "recharge" 数据库中记录的某些属性。最好的方法是什么?我需要使用 gem 吗?

我正在为我的 ORM 使用 rails 4.2.6、ruby 2.3.0 和活动记录。

在您想要 "refresh" 的模型中,您可以设置静态方法:

# 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

那么,我建议你定义一些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

然后,您可以使用 whenever gem 在您的 cron 选项卡中设置您的日程安排,这要归功于一个不错的 dsl:

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

当您使用 capistrano to deploy your app: In that case use the whenever capistrano integration 在每次部署时自动刷新您的 cron 选项卡时,一个巨大的胜利。

排程愉快