Erik's Engineering

something alliterative

Quick tip: Thread.new in IRB

The other day I found myself typing the following into IRB. I wanted a quick and dirty way to get some time series data about a job queue and this is what I came up with.

@queue_stats_list = []
Thread.new do
  queue_name = 'worq.test'
  while true do
    @queue_stats_list << QueueStats.new(queue_name)
    sleep 30
  end

  puts "Sampler thread exiting"
end

Thread.new will run whatever block you give it in a separate thread. It's in the same process, so you have access to shared variables. I'm just using @queue_stats_list to accumulate some data in memory. I can always call @queue_stats_list.last to get the most recent or compare different readings to see how things changed over time. It'll keep going as long as your console is running.

Eventually this grew into a much more full-featured class that knows how to calculate rates of change between measurements and all sorts of other goodies, but the first cut took no more than 5 minutes (including that QueueStats class I'm not showing you) and got me enough data to say "This job queue won't complete for a week or more. I'm going to have to figure out what's slowing it down and fix it."

With ruby, threads don't have to be reserved for fancy infrastructure projects. Any time you're in a console you've got concurrency at your fingertips.

Published on 28/05/2012 at 17h24 .

Comment Quick tip: Thread.new in IRB

Trackbacks are disabled

Powered by Typo – Thème Frédéric de Villamil | Photo Glenn