更新控制器变量在设置时间间隔 - Updating controller variable at set interval

- 此内容更新于:2016-02-01
主题:

我现在有以下简单的控制器:是一个相当昂贵的操作虽然上述工作,我不想每次刷新页面运行它。我怎么能解耦的更新,更新的一个固定的时间表,假设每15分钟。每次页面加载它只会返回当前@results值,而在最坏的情况下将14分59秒过时了。

原文:

I currently have the following simple controller:

class SimpleController < ApplicationController
  def index
    @results = fetch_results
  end
end

fetch_results is a fairly expensive operation so although the above works, I don't want to run it every time the page is refreshed. How can I decouple the updating of @results so that it's updated on a fixed schedule, let's say every 15 minutes.

That way each time the page is loaded it will just return the current @results value, which at worst would be 14 minutes and 59 seconds out of date.

网友:结果存储在一个数据库表和另外一个时间戳检查之前昂贵的op。如果超过15分钟的时间戳,做手术,否则从数据库中使用缓存的结果。

(原文:Store the result in a db table and additionally a timestamp which is checked before the time expensive op is done. If the timestamp is older than 15 minutes, do the operation, otherwise use the cached result from the database.)

网友:你能把你的代码?

(原文:Can you post your fetch_results code?)

解决方案:
你可能想要使用Rails的低水平缓存:阅读更多关于如何配置Rails的缓存存储在Rails指南。
原文:

You might want to use Rails` low level caching for this:

def index
  @results = Rails.cache.fetch('fetched_results', expires_in: 15.minutes) do
    fetch_results
  end
end

Read more about how to configure Rails' caching stores in the Rails Guide.

解决方案:
我将存储在一个数据库表,定期更新通过背景的工作。更新将会相对于一些事件,比如如果用户所做的事情可能会改变结果,那么结果将是重新计算和更新。另一个解决方案是定期更新,说每小时,使用cron作业。有一个很好的宝石,可以处理它。
原文:

Well I would store this in a database table and update regularly via a background job. The updates will be relative to some events, like if the user has done something that may change the result, then the result will be recalculated and updated.

Another solution is to update the result regularly, say every hour, using cron jobs. There is a good gem that can handle it.