Class: RJR::EMAdapter
Overview
EventMachine adapater interface, ties reactor lifecycle to an instance of this class.
Instance Attribute Summary collapse
-
#reactor_thread ⇒ Object
Run reactor in its own interally managed thread.
Instance Method Summary collapse
-
#halt ⇒ Object
Halt the reactor if running.
-
#initialize ⇒ EMAdapter
constructor
EMAdapter initializer.
-
#join ⇒ Object
Block until reactor thread is terminated.
-
#method_missing(method_id, *args, &bl) ⇒ Object
Delegates everything else directly to eventmachine (eg schedule, add_timer, add_periodic_timer, reactor_running?, stop_event_loop, etc).
-
#start ⇒ Object
Start the eventmachine reactor thread if not running.
Constructor Details
#initialize ⇒ EMAdapter
EMAdapter initializer
17 18 19 20 21 22 23 24 |
# File 'lib/rjr/util/em_adapter.rb', line 17 def initialize @em_lock = Mutex.new EventMachine.error_handler { |e| puts "EventMachine raised critical error #{e} #{e.backtrace}" # TODO dispatch to registered event handlers } end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_id, *args, &bl) ⇒ Object
Delegates everything else directly to eventmachine
(eg schedule, add_timer, add_periodic_timer,
reactor_running?, stop_event_loop, etc)
67 68 69 70 71 |
# File 'lib/rjr/util/em_adapter.rb', line 67 def method_missing(method_id, *args, &bl) @em_lock.synchronize{ EventMachine.send method_id, *args, &bl } end |
Instance Attribute Details
#reactor_thread ⇒ Object
Run reactor in its own interally managed thread
14 15 16 |
# File 'lib/rjr/util/em_adapter.rb', line 14 def reactor_thread @reactor_thread end |
Instance Method Details
#halt ⇒ Object
Halt the reactor if running
50 51 52 53 |
# File 'lib/rjr/util/em_adapter.rb', line 50 def halt self.stop_event_loop if self.reactor_running? self end |
#join ⇒ Object
Block until reactor thread is terminated
58 59 60 61 62 |
# File 'lib/rjr/util/em_adapter.rb', line 58 def join th = @em_lock.synchronize{ @reactor_thread } th.join unless th.nil? self end |
#start ⇒ Object
Start the eventmachine reactor thread if not running
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/rjr/util/em_adapter.rb', line 27 def start @em_lock.synchronize{ # TODO on event of the process ending this thread will be # shutdown before a local finalizer can be run, # would be good to gracefully shut this down / wait for completion @reactor_thread = Thread.new { begin EventMachine.run rescue Exception => e # TODO option to autorestart the reactor on errors ? puts "Critical exception #{e}\n#{e.backtrace.join("\n")}" ensure @em_lock.synchronize { @reactor_thread = nil } end } unless @reactor_thread } sleep 0.01 until EventMachine.reactor_running? # XXX hack but needed self end |