Created
January 31, 2010 13:58
-
-
Save jqr/291079 to your computer and use it in GitHub Desktop.
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
# Useful in JRuby environment where Timeout and SystemTimer are not working as expected. | |
class ThreadedTimeout | |
def self.realtime(timeout, options = {}) | |
resolution = options[:resolution] || 1 | |
begin | |
start = Time.now | |
resolution ||= 1 | |
mutex = Mutex.new | |
thread = Thread.new do | |
mutex.synchronize do | |
yield | |
end | |
end | |
(timeout.to_f / resolution).ceil.times { sleep resolution; break if mutex.try_lock } | |
ensure | |
duration = Time.now - start | |
thread.kill | |
end | |
duration | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment