Quick tip - Flexible session sweeping
November 10th, 2006
Quick tips
Rails
Need to clean up your old sessions?
I picked up on the idea of using a shell ActiveRecord class to sweep old sessions by someone on the mailing list a long time ago. I simply tweaked the idea to accept flexible time parameters.
class Session < ActiveRecord::Base
# time_ago examples:
# 30m => 30 minutes
# 1h => 1 hour
# 3d => 3 days
def self.sweep(time_ago = nil)
time = case time_ago
when /^(\d+)m$/ then Time.now.utc - $1.to_i.minute
when /^(\d+)h$/ then Time.now.utc - $1.to_i.hour
when /^(\d+)d$/ then Time.now.utc - $1.to_i.day
else Time.now.utc - 1.hour
end
self.delete_all "updated_on < '#{time.to_s(:db)}'"
end
end
Now just schedule with cron...
$ crontab -e
# Delete old session after 3 hours of no use. Run every 15 minutes.
*/15 * * * * /usr/local/bin/ruby /var/www/apps/cool_app/current/script/runner -e production "Session.sweep('3h')"


Commenting is closed for this article.