Class: God::Driver

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

Overview

DriverEvent

Constant Summary collapse

INTERVAL =
0.25

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(task) ⇒ Driver

Instantiate a new Driver and start the scheduler loop to handle events

+task+ is the Task this Driver belongs to

Returns Driver



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/god/driver.rb', line 30

def initialize(task)
  @task = task
  @events = []
  @ops = Queue.new
  
  @thread = Thread.new do
    loop do
      begin
        if !@ops.empty?
          self.handle_op
        elsif !@events.empty?
          self.handle_event
        else
          sleep INTERVAL
        end
      rescue Exception => e
        message = format("Unhandled exception in driver loop - (%s): %s\n%s",
                         e.class, e.message, e.backtrace.join("\n"))
        applog(nil, :fatal, message)
      end
    end
  end
end

Instance Attribute Details

#threadObject (readonly)

Returns the value of attribute thread.



22
23
24
# File 'lib/god/driver.rb', line 22

def thread
  @thread
end

Instance Method Details

#clear_eventsObject

Clear all events for this Driver

Returns nothing



80
81
82
# File 'lib/god/driver.rb', line 80

def clear_events
  @events.clear
end

#handle_eventObject

Handle the next event (poll condition) that is due

Returns nothing



65
66
67
68
69
70
71
72
73
74
75
# File 'lib/god/driver.rb', line 65

def handle_event
  if @events.first.due?
    event = @events.shift
    @task.handle_poll(event.condition)
  end
  
  # don't sleep if there is a pending event and it is due
  unless @events.first && @events.first.due?
    sleep INTERVAL
  end
end

#handle_opObject

Handle the next queued operation that was issued asynchronously

Returns nothing



57
58
59
60
# File 'lib/god/driver.rb', line 57

def handle_op
  command = @ops.pop
  @task.send(command[0], *command[1])
end

#message(name, args = []) ⇒ Object

Queue an asynchronous message

+name+ is the Symbol name of the operation
+args+ is an optional Array of arguments

Returns nothing



89
90
91
# File 'lib/god/driver.rb', line 89

def message(name, args = [])
  @ops.push([name, args])
end

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

Create and schedule a new DriverEvent

+condition+ is the Condition
+delay+ is the number of seconds to delay (default: interval defined in condition)

Returns nothing



98
99
100
101
102
103
104
105
# File 'lib/god/driver.rb', line 98

def schedule(condition, delay = condition.interval)
  applog(nil, :debug, "driver schedule #{condition} in #{delay} seconds")
  
  @events.concat([DriverEvent.new(condition, delay)])
  
  # sort events
  @events.sort! { |x, y| x.at <=> y.at }
end