Class: Gamelan::Timer

Inherits:
Object
  • Object
show all
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

Scheduler

Instance Attribute Summary collapse

Instance Method Summary collapse

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(options = {})
  self.tempo = options.fetch(:tempo, 120)
  @rate      = 1.0 / options.fetch(:rate, 1000)
  @sleep_for = rate / 10.0
end

Instance Attribute Details

#phaseObject (readonly)

Returns the value of attribute phase.



5
6
7
# File 'lib/gamelan/timer.rb', line 5

def phase
  @phase
end

#rateObject (readonly)

Returns the value of attribute rate.



5
6
7
# File 'lib/gamelan/timer.rb', line 5

def rate
  @rate
end

#timeObject (readonly)

Returns the value of attribute time.



5
6
7
# File 'lib/gamelan/timer.rb', line 5

def time
  @time
end

Instance Method Details

#joinObject



46
# File 'lib/gamelan/timer.rb', line 46

def join; @thread.join end

#runObject

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

#stopObject

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

#tempoObject

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