Class: God::Timer

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

Constant Summary collapse

INTERVAL =
0.25
@@timer =
nil

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTimer

Start the scheduler loop to handle events



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
# File 'lib/god/timer.rb', line 28

def initialize
  @events = []
  @mutex = Mutex.new
  
  @timer = Thread.new do
    loop do
      # get the current time
      t = Time.now.to_i
      
      # iterate over each event and trigger any that are due
      @events.each do |event|
        if t >= event.at
          self.trigger(event)
          @mutex.synchronize do
            @events.delete(event)
          end
        else
          break
        end
      end
      
      # sleep until next check
      sleep INTERVAL
    end
  end
end

Instance Attribute Details

#eventsObject (readonly)

Returns the value of attribute events.



15
16
17
# File 'lib/god/timer.rb', line 15

def events
  @events
end

#timerObject (readonly)

Returns the value of attribute timer.



15
16
17
# File 'lib/god/timer.rb', line 15

def timer
  @timer
end

Class Method Details

.getObject



19
20
21
# File 'lib/god/timer.rb', line 19

def self.get
  @@timer ||= Timer.new
end

.resetObject



23
24
25
# File 'lib/god/timer.rb', line 23

def self.reset
  @@timer = nil
end

Instance Method Details

#joinObject

Join the timer thread



75
76
77
# File 'lib/god/timer.rb', line 75

def join
  @timer.join
end

#schedule(condition, interval = condition.interval) ⇒ Object

Create and register a new TimerEvent with the given parameters



56
57
58
59
60
61
# File 'lib/god/timer.rb', line 56

def schedule(condition, interval = condition.interval)
  @mutex.synchronize do
    @events << TimerEvent.new(condition, interval)
    @events.sort! { |x, y| x.at <=> y.at }
  end
end

#trigger(event) ⇒ Object



70
71
72
# File 'lib/god/timer.rb', line 70

def trigger(event)
  Hub.trigger(event.condition)
end

#unschedule(condition) ⇒ Object

Remove any TimerEvents for the given condition



64
65
66
67
68
# File 'lib/god/timer.rb', line 64

def unschedule(condition)
  @mutex.synchronize do
    @events.reject! { |x| x.condition == condition }
  end
end