Class: Rednode::Scheduler

Inherits:
Object
  • Object
show all
Defined in:
lib/rednode/timer.rb

Defined Under Namespace

Classes: Timer

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeScheduler

Returns a new instance of Scheduler.



6
7
8
9
# File 'lib/rednode/timer.rb', line 6

def initialize
  @timers = []
  @running = false
end

Instance Attribute Details

#runningObject (readonly)

Returns the value of attribute running.



4
5
6
# File 'lib/rednode/timer.rb', line 4

def running
  @running
end

#timersObject (readonly)

Returns the value of attribute timers.



4
5
6
# File 'lib/rednode/timer.rb', line 4

def timers
  @timers
end

Instance Method Details

#add_periodic_timer(interval, &block) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/rednode/timer.rb', line 21

def add_periodic_timer(interval, &block)
  Timer.new(self).tap do |timer|
    timer.periodic = true
    timer.interval = interval
    timer.callback = block
    @timers << timer
    timer.start if @running
  end
end

#add_timer(interval, &block) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/rednode/timer.rb', line 11

def add_timer(interval, &block)
  Timer.new(self).tap do |timer|
    timer.periodic = false
    timer.interval = interval
    timer.callback = block
    @timers << timer
    timer.start if @running
  end
end

#next_tick(&block) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/rednode/timer.rb', line 52

def next_tick(&block)
  if @running
    EventMachine.next_tick do
      yield
    end
  else
    add_timer(0) { yield }
  end
end

#remove_timer(timer) ⇒ Object



31
32
33
# File 'lib/rednode/timer.rb', line 31

def remove_timer(timer)
  @timers.delete(timer)
end

#start_loopObject



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rednode/timer.rb', line 35

def start_loop
  EventMachine.run do
    @running = true
    @timers.each do |t|
      t.start unless t.running
    end
    
    EventMachine::PeriodicTimer.new(0.05) do
      stop_loop if @timers.size == 0
    end
  end
end

#stop_loopObject



48
49
50
# File 'lib/rednode/timer.rb', line 48

def stop_loop
  EventMachine.stop_event_loop
end