I have a long database query on one of our dashboard systems that I would like to cache as results do not need to be accurate in realtime but can give a "close enough" value from the cache.
I would like to do this without the user ever having to wait. I was looking at using something like
Rails.cache.write('my_val', 'val', :expires_in => 60.minutes)
to store this value, but I don't believe it gives the exact functionality that I want. I would like to call with
Rails.fetch('my_val') { create a background task to update my_val; return expired my_val}
It seems that my_val is removed from the cache when it expired though. Is there any way to access this expired value or perhaps another built in mechanism that would enable this functionality?
Thanks.
Just do this:
Rails.cache.write('my_val', 'val')
never expire
Now run your background job:
SomeLongJob.process
In the SomeLongJob.process job do this:
def SomeLongJob.process
some_long_calculation = Blah.calc
Rails.cache.write('my_val', some_long_calculation)
end
Now read the data with
def get_value
val = Rails.cache.read('my_val', 'val')
end
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