I needed to expire caches using jobs. If I used an observer or a sweeper the updates would happen to often. I was displaying the info of a bunch of records (foobars) on a single view and I didn’t want it to update every time a Foobar was created – that would be too often and reduce the benefits of caching.
Instead I wanted a job that ran every hour to expire the cache.
- First, I installed the Whenever gem which updates the cron file and helping you schedule server jobs.
- use the command `wheneverize .` to generate the schedule.rb file for Whenever
- I created a new rake file, “expire_cache.rake” in lib/tasks
- In the file, I put this:task :expire_cache_1_hour => :environment do
puts “———————expiring 1 hour cache————-”
ActionController::Base.new.expire_fragment(“foobar”) #I already had <% cache(‘foobar’) do %> in my view
- In the schedule.rb file used by Whenever, I added:every 1.hour do