在给定的时间间隔后,我可以定期重新计算属性吗? [英] Can I periodically recalculate an attribute after a given time interval?

查看:153
本文介绍了在给定的时间间隔后,我可以定期重新计算属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型User,有一个float属性Value。我想让每个用户的价值在用户创建后每24小时贬值1%(即乘以0.99)。例如,如果用户在1月1日的02:34,1月2日的02:34创建了值为5的用户,则其值应重新计算为4.95。然后在1月3日02:34,应该重新计算为4.9005,依此类推。



可以这样做吗?



我使用的是Rails 4.0.10应用程式,

解决方案

使用 delayed_job gem你可以这样做:

 #in user.rb 
after_create:decrease_value_periodically

private
def decrease_value_periodically
self.value = value * 0.99
self.save!

decrease_value_periodically如果value> 0
end
handle_asynchronously:decrease_value_periodically,
:run_at => Proc.new {24.hours.from_now}

此示例将在创建用户后24小时运行






另一个选项可能是每天的Cron任务重新计算所有用户的值同时(例如午夜)。你可以设置一个Cron任务运行一个Rails方法,像这样:

 #命令为Cron 
rails .recalculate_all_values

#在user.rb中
def self.recalculate_all_values
User.all.each {| user | user.decrease_value}
end

private
def decrease_value
如果值> 0
self.value = value * 0.99
self.save!
end
end

IMO这取决于你的优先级:精确运行24小时后,选择delayed_jobs。虽然Cron解决方案更容易维护,但是您可能最终将值递减为早或晚(假设用户在晚上11点创建,一小时后Cron任务开始第一次降低值)。


I have a model "User", with a float attribute "Value". I want each User's Value to depreciate 1%(i.e., be multiplied by 0.99) every 24 hours after the User's creation. For example, if a User is created with a Value of 5 at 02:34 on January 1st, then at 02:34 on January 2nd, its value should be recalculated to be 4.95. Then at 02:34 on January 3rd, it should be recalculated to be 4.9005, and so on.

Can this be done?

I'm using a Rails 4.0.10 app, if that matters.

解决方案

With the delayed_job gem you could do something like this:

# in user.rb
after_create :decrease_value_periodically

private
def decrease_value_periodically
  self.value = value * 0.99
  self.save!

  decrease_value_periodically if value > 0
end
handle_asynchronously :decrease_value_periodically, 
                      :run_at => Proc.new { 24.hours.from_now }

This example would run 24 hours after creation of an user and would reschedule itself over and over again.


Another option might be a daily Cron task that recalculates all user's values at the same time (midnight for example). You could setup a Cron task that runs a Rails method like this:

# command for Cron
rails runner "User.recalculate_all_values"

# in user.rb
def self.recalculate_all_values
  User.all.each { |user| user.decrease_value }
end

private
def decrease_value
  if value > 0
    self.value = value * 0.99
    self.save!
  end
end

IMO it depends on your priorities: If you want a precise run after 24 hours, choose delayed_jobs. Whereas the Cron solution is easier to maintain, but you might end up with decreasing values to early or to late (Imagine a user is created at 11pm and one hour later the Cron task starts to decrase the value for the first time).

这篇关于在给定的时间间隔后,我可以定期重新计算属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆