class TTY::Prompt::Timeout
Constants
- Error
- TIMEOUT_HANDLER
Public Class Methods
new(options = {})
click to toggle source
# File lib/tty/prompt/timeout.rb, line 12 def initialize(options = {}) @timeout_handler = options.fetch(:timeout_handler) { TIMEOUT_HANDLER } @interval_handler = options.fetch(:interval_handler) { proc {} } @lock = Mutex.new @running = true @timers = Timers::Group.new end
timeout(time, interval, &block)
click to toggle source
# File lib/tty/prompt/timeout.rb, line 20 def self.timeout(time, interval, &block) (@scheduler ||= new).timeout(time, interval, &block) end
Public Instance Methods
async_run(time, interval)
click to toggle source
# File lib/tty/prompt/timeout.rb, line 38 def async_run(time, interval) Thread.new do Thread.current.abort_on_exception = true start = Time.now interval_timer = @timers.every(interval) do runtime = Time.now - start delta = time - runtime if delta.round >= 0 @interval_handler.(delta.round) end end while @running @lock.synchronize { @timers.wait runtime = Time.now - start delta = time - runtime if delta <= 0.0 @timeout_handler.(Thread.current) break end } end interval_timer.cancel end end
timeout(time, interval, &block)
click to toggle source
Evalute block and time it
@param [Float] time
the time by which to stop
@param [Float] interval
the interval time for each tick
@api public
# File lib/tty/prompt/timeout.rb, line 32 def timeout(time, interval, &block) @runner = async_run(time, interval) @running = block.() @runner.join end