Skip to content

Instantly share code, notes, and snippets.

@pjaspers
Created March 10, 2017 21:32
Show Gist options
  • Save pjaspers/7b3d1ce35933539b367cd56040466ca7 to your computer and use it in GitHub Desktop.
Save pjaspers/7b3d1ce35933539b367cd56040466ca7 to your computer and use it in GitHub Desktop.
#! /usr/bin/env ruby
#
# Either `chmod +x` me or run me as `ruby ruby-signals`
total = 1000000000
index = 0
start_time = Time.now
sleep_for = 0.1
wat = <<WAT
Hi there, this shows how to instrument a long running CLI process so you
can get some more info out of it.
It's going from #{index} to #{total} with a sleep interval of #{sleep_for}s.
It will print each item it is currently handling. Great, much insight!
Hold on. There's this thing called signals you can send to each and every
UNIX program and a well behaved UNIX program will listen to them. For example
look here how unicorn uses this to handle zero downtime deploys:
https://bogomips.org/unicorn/SIGNALS.html
So let's add this to our long running program as well. Try it,
\033[33;5mPress Control-T\033[0m
You will now see additional information about the process. Just for bonus
I've also trapped the Interrupt signal so it displays a nicer end message.
So go ahead:
Press Control-C
COMPUTERING BELOW
||
WAT
def humanize secs
[[60, :seconds], [60, :minutes], [24, :hours], [1000, :days]].map{ |count, name|
if secs > 0
secs, n = secs.divmod(count)
"#{n.to_i} #{name}"
end
}.compact.reverse.join(' ')
end
Signal.trap("INFO") do
info_time = Time.now
timestamp = info_time.strftime("%H:%M:%S")
if index > 0
remaining = total - index
average_per_second = (info_time - start_time)/index.to_f
remaining_time = humanize(remaining*average_per_second)
puts "%s [R: %d | A: %.2f/s| E: %s]" % [timestamp, remaining, average_per_second, remaining_time]
else
puts "%s - 0 processed yet" % [timestamp]
end
end
Signal.trap("INT") do
puts "So long!"
exit
end
puts wat
(0..total).lazy.each do |i|
index = i
STDOUT.print "#{index}\r"
sleep sleep_for
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment