Expiring Cache on Rails Using Jobs

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.

  1. First, I installed the Whenever gem which updates the cron file and helping you schedule server jobs.
  2. use the command `wheneverize .` to generate the schedule.rb file for Whenever
  3. I created a new rake file, “expire_cache.rake” in lib/tasks
  4. 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
  5. In the schedule.rb file used by Whenever, I added:every 1.hour do
    rake “expire_cache_1_hour”

Running Memcached on Windows

I needed to run memcached locally on my Windows PC.  These are the steps to making it work on Windows.

(1) Download the Memcached program (32 bit)

(2) Extract the exe to C:\memcached

(3) Open your start menu

(4) In the Search box at the bottom, enter “cmd” – don’t hit enter!

(5) Instead of enter, press Ctrl+Shift + Enter.  This should allow you to run the command prompt as the administrator, as long as your Windows user ID is set-up as an admin

(6) use the `cd` command to navigate to get to: C:\memcached

(7) once there, enter: memcached.exe -d install

(8) next enter: memcached.exe -d start

You should now be running a memcached server.  To check, open the Windows Task manager and on the Services tab, you should see “memcached”.