Class: TTY2::Prompt::Timer
- Inherits:
-
Object
- Object
- TTY2::Prompt::Timer
- Defined in:
- lib/tty2/prompt/timer.rb
Instance Attribute Summary collapse
-
#duration ⇒ Object
readonly
Returns the value of attribute duration.
-
#interval ⇒ Object
readonly
Returns the value of attribute interval.
-
#total ⇒ Object
readonly
Returns the value of attribute total.
Instance Method Summary collapse
-
#initialize(duration, interval) ⇒ Timer
constructor
A new instance of Timer.
- #on_tick(&block) ⇒ Object
- #runtime ⇒ Object
- #start ⇒ Object
- #stop ⇒ Object
-
#time_now ⇒ Object
Object represeting current time.
- #while_remaining ⇒ Object
Constructor Details
#initialize(duration, interval) ⇒ Timer
Returns a new instance of Timer.
12 13 14 15 16 17 18 |
# File 'lib/tty2/prompt/timer.rb', line 12 def initialize(duration, interval) @duration = duration @interval = interval @total = 0.0 @current = nil @events = [] end |
Instance Attribute Details
#duration ⇒ Object (readonly)
Returns the value of attribute duration.
6 7 8 |
# File 'lib/tty2/prompt/timer.rb', line 6 def duration @duration end |
#interval ⇒ Object (readonly)
Returns the value of attribute interval.
10 11 12 |
# File 'lib/tty2/prompt/timer.rb', line 10 def interval @interval end |
#total ⇒ Object (readonly)
Returns the value of attribute total.
8 9 10 |
# File 'lib/tty2/prompt/timer.rb', line 8 def total @total end |
Instance Method Details
#on_tick(&block) ⇒ Object
36 37 38 |
# File 'lib/tty2/prompt/timer.rb', line 36 def on_tick(&block) @events << block end |
#runtime ⇒ Object
32 33 34 |
# File 'lib/tty2/prompt/timer.rb', line 32 def runtime time_now - @current end |
#start ⇒ Object
20 21 22 23 24 |
# File 'lib/tty2/prompt/timer.rb', line 20 def start return if @current @current = time_now end |
#stop ⇒ Object
26 27 28 29 30 |
# File 'lib/tty2/prompt/timer.rb', line 26 def stop return unless @current @current = nil end |
#time_now ⇒ Object
Object represeting current time
64 65 66 |
# File 'lib/tty2/prompt/timer.rb', line 64 def time_now ::Process.clock_gettime(Process::CLOCK_MONOTONIC) end |
#while_remaining ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/tty2/prompt/timer.rb', line 40 def while_remaining start remaining = duration if @duration while remaining >= 0.0 if runtime >= total tick = duration - @total @events.each { |block| block.(tick) } @total += @interval end yield(remaining) remaining = duration - runtime end else loop { yield } end ensure stop end |