0

I'm working on a project where i want to do a mysql query from time to time. The query is too long, and actually it's done when the user does a request.

I'm afraid if many users does the request, the application will be too slow to respond. So, I want to do the query and load it with the query response from time to time, and then, on a request, the action from the controller will use this variable, instead of doing the query again and again.

How can I do that using Whenever?

on the schedule.rb

every 5.minutes do
    runner "variable = Model.method"
end

and on the controller

def some_action
"the variable should be loaded here"

end
Hugo Tamaki
  • 41
  • 1
  • 7
  • This is the completely wrong way to go about it. Use caching: http://stackoverflow.com/questions/5709773/how-to-cache-a-query-in-ruby-on-rails-3. – Damien Roche Oct 24 '13 at 16:48

1 Answers1

0

I agree with Damien Roche, you need to cache the results of the query. But, I don't think the example he gives is the best answer for you because you don't want for a user to wait for the query when it isn't cached, at the times when the cache is expired, even if this is a rare occurrence. So you need to combine the periodic query with whenever, like you suggested, with a caching mechanism to store your query result, and retrieve it from the cache in your controller. since the runner is a different process, you will have to use a cache that is available to both the runner and your app. I recommend you look into Redis. it should be very simple to get it to work so that the runner runs the query and when it finishes writes a result set to the Redis cahce. The controller will then read the result set from the cache.

  • I combined both, used Whenever schedules to call a method from time to time, and caching it, then on the controller, i'm getting the value with Rails.cache.read(). That made the application run much faster. – Hugo Tamaki Oct 28 '13 at 21:50