Skip to content

Instantly share code, notes, and snippets.

@jonathanstrong
Last active March 22, 2019 07:01
Show Gist options
  • Save jonathanstrong/aed30cd51de3f52a275af046e547786b to your computer and use it in GitHub Desktop.
Save jonathanstrong/aed30cd51de3f52a275af046e547786b to your computer and use it in GitHub Desktop.
ruby simple event loop with ctrl-c handling
#!/usr/bin/ruby
require 'date'
# see also https://github.com/socketry/nio4r
last = Time.now.utc
stop = false
trap("SIGINT") do
puts "caught sigint"
stop |= true
end
n = 0
loop do
loop_time = Time.now.utc
n += 1
if loop_time - last > 1
puts "#{loop_time} #{n} stop = #{stop}"
last = loop_time
if stop # odd place for this - it's to demonstrate ctrl-c doesn't immediately exit
break
end
else
sleep(0.1) # anything faster than this caused noticeable cpu
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment