Following the advice of the Agile Web Development with Rails book, I sought to clear out sessions periodically from the Scrawlers database. I also took a hint from and put the work directly in Rails, using script/runner to execute. Specifically I created a new model class: SessionCleaner (/app/models/session_cleaner.rb).

class SessionCleaner
  def self.remove_stale_sessions
      destroy_all( ['updated_at < ?', 12.hours.ago] ) 

I figured I’d clear any sessions that are 12 hours old or greater. Good deal. I don’t need to run this cleaner too frequently, so I scheduled it to run on Dreamhost every hour in my staging and production environment. Each job will run on 1/2 hour offsets.

#minute hour mday month wday command
0 */1 * * * ruby ~/ -e staging "SessionCleaner.remove_stale_sessions"
30 */1 * * * ruby ~/ -e production "SessionCleaner.remove_stale_sessions"

The above is a cron specification; cron being used to schedule jobs in the *nix environment. I created it in ~/mycrontab. Using the shell command “crontab ~/mycrontab”, I was able to add my newly created specification to the schedule. If I make any updates to ~/mycrontab I’ll need to resubmit the specification to the schedule. (I checked out the helpful Dreamhost knowledge base to make sure I was croning as Dreamhost wanted me to cron.)

One thing to keep in mind: do not allow those cron specifications to wrap to a second line. There will be no scheduled jobs in your future if you do. This is a little skitchy using nano as an editor because it likes to wrap things around. I’m sure you’ll figure out how to fool little old nano, though.

Mar 09, 2007 · Subscribe · Archive · Projects · Twitter · GitHub · Flickr