Rake Task to Clear Expired Session Files

Perhaps some guys who came to Rails from PHP expected session expiry to be handled automatically. But in Rails we have to deal with it ourselves. There’s an awesome article on the topic. The main idea is that we need to clear expired sessions which were not accessed for some time and the ones which were created a long time ago. I’ve tried to find a ready-made script for this purpose, but found the ones that deal with database based sessions only, so decided to write it myself.

require 'find'

namespace :tmp do
  namespace :sessions do
    desc 'Clear expired sessions'
    task :clear_expired => :environment do
      ctime = (ENV['ctime'] || 120).to_i
      atime = (ENV['atime'] ||  30).to_i
      Find.find(RAILS_ROOT + "/tmp/sessions/") do |path|
        if FileTest.directory?(path)
          if File.basename(path)[0] == ?.
            Find.prune
          else
            next
          end
        else
          File.delete(path) if File.ctime(path) < ctime.minutes.ago or File.atime(path) < atime.minutes.ago
        end
      end
    end
  end
end

It can be run with 2 optional parameters: “atime”, which defines the time in minutes that will be compared against the last access time of a session file and “ctime” which defines the time in minutes that will be compared against the creation time of a session file. The default values are: ctime = 120 (minutes) and atime = 20 (miuntes) which means that the session files not accessed in the last 20 minutes and created earlier than 2 hours ago will be removed when the script runs.

You can run it like this (I’m overriding default time parameters in the example):

rake tmp:sessions:clear_expired atime=15 ctime=60

Of course you’ll set up a cron to run the script periodiacally and clear expired sessions for you, but please note that the actuall maximum session lifetime will be atime + the time between 2 script runs.