Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating controller variable at set interval

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.

like image 651
imrichardcole Avatar asked Feb 07 '23 21:02

imrichardcole


2 Answers

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.

like image 194
spickermann Avatar answered Feb 15 '23 22:02

spickermann


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.

like image 41
mtkcs Avatar answered Feb 16 '23 00:02

mtkcs