Skip to content

Instantly share code, notes, and snippets.

@jqr
Created January 31, 2010 13:58
Show Gist options
  • Save jqr/291079 to your computer and use it in GitHub Desktop.
Save jqr/291079 to your computer and use it in GitHub Desktop.
# 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