Class: Gamelan::Timer
- Inherits:
-
Object
- Object
- Gamelan::Timer
- Defined in:
- lib/gamelan/timer.rb
Overview
The Timer is responsible for executing code at a fixed rate. Users must subclass Gamelan::Timer
. See Gamelan::Scheduler
for an example.
Direct Known Subclasses
Instance Attribute Summary collapse
-
#phase ⇒ Object
readonly
Returns the value of attribute phase.
-
#rate ⇒ Object
readonly
Returns the value of attribute rate.
-
#time ⇒ Object
readonly
Returns the value of attribute time.
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ Timer
constructor
Construct a new timer.
- #join ⇒ Object
-
#run ⇒ Object
Initialize the scheduler’s clock, and begin executing tasks.
-
#stop ⇒ Object
Halt the scheduler.
-
#tempo ⇒ Object
Current tempo, in bpm.
-
#tempo=(bpm) ⇒ Object
Set the tempo in bpm.
Constructor Details
#initialize(options = {}) ⇒ Timer
Construct a new timer. Timer#run must be called explicitly once a Timer is created. Accepts two options, :tempo
and :rate
.
:tempo
-
The timer’s tempo, in bpm. For example, at :tempo => 120,
the timer’s logical phase
will advance by 2.0 every 60 seconds.
:rate
-
Frequency in Hz at which the scheduler will dispatch.
12 13 14 15 16 |
# File 'lib/gamelan/timer.rb', line 12 def initialize( = {}) self.tempo = .fetch(:tempo, 120) @rate = 1.0 / .fetch(:rate, 1000) @sleep_for = rate / 10.0 end |
Instance Attribute Details
#phase ⇒ Object (readonly)
Returns the value of attribute phase.
5 6 7 |
# File 'lib/gamelan/timer.rb', line 5 def phase @phase end |
#rate ⇒ Object (readonly)
Returns the value of attribute rate.
5 6 7 |
# File 'lib/gamelan/timer.rb', line 5 def rate @rate end |
#time ⇒ Object (readonly)
Returns the value of attribute time.
5 6 7 |
# File 'lib/gamelan/timer.rb', line 5 def time @time end |
Instance Method Details
#join ⇒ Object
46 |
# File 'lib/gamelan/timer.rb', line 46 def join; @thread.join end |
#run ⇒ Object
Initialize the scheduler’s clock, and begin executing tasks.
19 20 21 22 23 24 25 26 27 |
# File 'lib/gamelan/timer.rb', line 19 def run return if @running @running = true @thread = Thread.new do @phase = 0.0 @origin = @time = Time.now.to_f loop { dispatch; advance } end end |
#stop ⇒ Object
Halt the scheduler. Note that the scheduler may be restarted, but is not resumable.
31 32 33 34 |
# File 'lib/gamelan/timer.rb', line 31 def stop @running = false @thread.kill end |
#tempo ⇒ Object
Current tempo, in bpm.
37 38 39 |
# File 'lib/gamelan/timer.rb', line 37 def tempo @tempo * 60.0 end |
#tempo=(bpm) ⇒ Object
Set the tempo in bpm.
42 43 44 |
# File 'lib/gamelan/timer.rb', line 42 def tempo=(bpm) @tempo = bpm / 60.0 end |