Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Caching, continue storing expired value

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.

like image 911
Peck Avatar asked Oct 23 '22 17:10

Peck


1 Answers

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
like image 152
drhenner Avatar answered Oct 27 '22 09:10

drhenner