Class: Scruby::Ticker

Inherits:
Object show all
Defined in:
lib/scruby/ticker.rb

Overview

A timer will call a given block periodically. The period is specified in beats per minute.

Direct Known Subclasses

Scheduler

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tempo = 120, size = 16, resolution = 1, loop = true, &block) ⇒ Ticker

Returns a new instance of Ticker.



16
17
18
19
20
21
# File 'lib/scruby/ticker.rb', line 16

def initialize tempo = 120, size = 16, resolution = 1, loop = true, &block
  @tempo , @resolution, @size, @loop = tempo , resolution, size, loop
  @interval   = 60.0 / @tempo
  @tick       = 0
  @block      = block
end

Instance Attribute Details

#intervalObject (readonly)

Returns the value of attribute interval.



13
14
15
# File 'lib/scruby/ticker.rb', line 13

def interval
  @interval
end

#loopObject

Returns the value of attribute loop.



14
15
16
# File 'lib/scruby/ticker.rb', line 14

def loop
  @loop
end

#resolutionObject

Returns the value of attribute resolution.



14
15
16
# File 'lib/scruby/ticker.rb', line 14

def resolution
  @resolution
end

#sizeObject

Returns the value of attribute size.



14
15
16
# File 'lib/scruby/ticker.rb', line 14

def size
  @size
end

#startObject (readonly)

Returns the value of attribute start.



13
14
15
# File 'lib/scruby/ticker.rb', line 13

def start
  @start
end

#tempoObject

Returns the value of attribute tempo.



14
15
16
# File 'lib/scruby/ticker.rb', line 14

def tempo
  @tempo
end

#tickObject (readonly)

Returns the value of attribute tick.



13
14
15
# File 'lib/scruby/ticker.rb', line 13

def tick
  @tick
end

Instance Method Details

#block(&block) ⇒ Object



25
26
27
# File 'lib/scruby/ticker.rb', line 25

def block &block
  @block = block
end

#dispatchObject



69
70
71
# File 'lib/scruby/ticker.rb', line 69

def dispatch
  @block.call index if @block
end

#indexObject



42
43
44
45
46
47
48
49
50
51
# File 'lib/scruby/ticker.rb', line 42

def index
  return @tick unless @size
  tick = @tick % @size
  if tick == 0 and @tick > 0 and !@loop
    stop
    nil
  else
    tick
  end
end

#next_timeObject



53
54
55
# File 'lib/scruby/ticker.rb', line 53

def next_time
  @next = @start + @tick * @interval
end

#runObject



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/scruby/ticker.rb', line 29

def run
  return self if @timer
  @start = Time.now
  @timer = EventMachine::PeriodicTimer.new @interval * 0.01 do
    if @next.nil? or Time.now >= @next
      dispatch
      @tick += @resolution
      next_time
    end
  end
  self
end

#running?Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/scruby/ticker.rb', line 65

def running?
  not @timer.nil?
end

#stopObject



57
58
59
60
61
62
63
# File 'lib/scruby/ticker.rb', line 57

def stop
  @timer.cancel if @timer
  @timer = nil
  @next  = nil
  @tick = 0
  self
end