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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With