Last active
March 22, 2019 07:01
-
-
Save jonathanstrong/aed30cd51de3f52a275af046e547786b to your computer and use it in GitHub Desktop.
ruby simple event loop with ctrl-c handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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