Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 7f8079b50e
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 92 lines (78 sloc) 1.774 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
module Scruby
  # Thread.new do
  # EventMachine.run do
  # EM.set_quantum 5
  # EM.error_handler do |e|
  # puts e
  # end
  # end
  # end
  
  # A timer will call a given block periodically. The period is specified in beats per minute.
  class Ticker
    attr_reader :start, :tick, :interval
    attr_accessor :tempo, :resolution, :size, :loop
    
    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
    
    named_args_for :initialize
    
    def block &block
      @block = block
    end

    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

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

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

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

    def running?
      not @timer.nil?
    end

    def dispatch
      @block.call index if @block
    end
  end

  class Scheduler < Ticker
    def initialize opts = {}
      super
      @queue = []
    end

    def dispatch
      if blocks = @queue[index]
        blocks.each{ |b| b.call }
      end
    end

    def at tick, &proc
      @queue[tick] ||= []
      @queue[tick].push proc
    end
  end
  
end
Something went wrong with that request. Please try again.