Posts Tagged ‘memcached’

script/memcached

Wednesday, November 18th, 2009

The inimitable Wincent recently referred to a memcached script he had written that toggled whether memcached is running or not. I thought that was a great idea so wrote my own and in the spirit of comparing dicks I thought I’d post it here.

#!/usr/bin/env ruby
 
 = ::File.expand_path(::File.dirname(__FILE__)) + '/../tmp/memcached.pid'
 
def process_id
  File.exist?() ? File.read().to_i : false
end
 
def running?
  if process_id 
    Process.kill(0, process_id) == 1 rescue false
  else
    false
  end
end
 
def start!
  print 'starting memcached ...'
  system "memcached -d -P #{} -l 127.0.0.1"
  sleep 0.5
  print "started with pid #{File.read}"
end
 
def stop!
  print 'stopping memcached ...'
  Process.kill('INT', process_id)
  sleep 0.5
  File.delete() if File.exist?()
  print 'done.'
  puts
end
 
def ensure_running
  running? ? puts('already running.') : start!
end
 
def ensure_stopped
  !running? ? puts('not running.') : stop!
end
 
def toggle
  running? ? stop! : start!
end
 
case ARGV.first
when 'start'
  ensure_running
when 'stop'
  ensure_stopped
when 'toggle'
  toggle
when 'status'
  running? ? puts('running') : puts('not running')
else
  toggle
end

I love writing these kinds of scripts in Ruby. It’s perfect for it.