Controller variable update at specified interval

I currently have the following simple controller:

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

fetch_results- A rather expensive operation, therefore, despite the above, I do not want to start it every time the page is updated. How can I separate an update @resultsso that it is updated on a fixed schedule, say every 15 minutes.

Thus, every time the page loads, it simply returns the current value @results, which in the worst case will be 14 minutes and 59 seconds out of date.

+4
source share
2 answers

You can use Rails low-level caching for this:

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

, Rails Rails.

+7

. , , -, , .

- result, , , cron. gem, .

+1

Source: https://habr.com/ru/post/1626742/


All Articles