-
-
Save microspino/dc38f7a6f76f52e56c2e3805f8ba171c to your computer and use it in GitHub Desktop.
Interruptible sleep in Ruby
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
module InterruptibleSleep | |
def interruptible_sleep(seconds) | |
@_sleep_check, @_sleep_interrupt = IO.pipe | |
IO.select([@_sleep_check], nil, nil, seconds) | |
end | |
def interrupt_sleep | |
@_sleep_interrupt.close if @_sleep_interrupt | |
end | |
end | |
class Test | |
include InterruptibleSleep | |
def start | |
puts "start" | |
interruptible_sleep 10 | |
puts "sleep interrupted!" | |
end | |
def stop | |
puts "stop" | |
interrupt_sleep | |
end | |
end | |
test = Test.new | |
Signal.trap('SIGINT') { test.stop } | |
test.start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment