Module: EventMachine::Synchrony
- Defined in:
- lib/em-synchrony.rb,
lib/em-synchrony/thread.rb,
lib/em-synchrony/em-multi.rb,
lib/em-synchrony/iterator.rb,
lib/em-synchrony/keyboard.rb,
lib/em-synchrony/tcpsocket.rb,
lib/em-synchrony/fiber_iterator.rb,
lib/em-synchrony/connection_pool.rb
Defined Under Namespace
Modules: Thread Classes: ConnectionPool, FiberIterator, Iterator, Keyboard, KeyboardHandler, Multi, TCPSocket
Class Method Summary collapse
- .add_periodic_timer(interval, &blk) ⇒ Object
- .add_timer(interval, &blk) ⇒ Object
-
.gets ⇒ Object
routes to EM::Synchrony::Keyboard.
-
.sleep(secs) ⇒ Object
a Fiber-aware sleep function using an EM timer.
-
.sync(df) ⇒ Object
sync is a close relative to inclineCallbacks from Twisted (Python).
Class Method Details
.add_periodic_timer(interval, &blk) ⇒ Object
74 75 76 77 78 |
# File 'lib/em-synchrony.rb', line 74 def self.add_periodic_timer(interval, &blk) EM.add_periodic_timer(interval) do Fiber.new { blk.call }.resume end end |
.add_timer(interval, &blk) ⇒ Object
68 69 70 71 72 |
# File 'lib/em-synchrony.rb', line 68 def self.add_timer(interval, &blk) EM.add_timer(interval) do Fiber.new { blk.call }.resume end end |
.gets ⇒ Object
routes to EM::Synchrony::Keyboard
81 82 83 |
# File 'lib/em-synchrony.rb', line 81 def self.gets EventMachine::Synchrony::Keyboard.new.gets end |
.sleep(secs) ⇒ Object
a Fiber-aware sleep function using an EM timer
62 63 64 65 66 |
# File 'lib/em-synchrony.rb', line 62 def self.sleep(secs) fiber = Fiber.current EM::Timer.new(secs) { fiber.resume } Fiber.yield end |
.sync(df) ⇒ Object
sync is a close relative to inclineCallbacks from Twisted (Python)
Synchrony.sync allows you to write sequential code while using asynchronous or callback-based methods under the hood. Example:
result = EM::Synchrony.sync EventMachine::HttpRequest.new(URL).get p result.response
As long as the asynchronous function returns a Deferrable object, which has a “callback” and an “errback”, the sync methond will automatically yield and automatically resume your code (via Fibers) when the call either succeeds or fails. You do not need to patch or modify the Deferrable object, simply pass it to EM::Synchrony.sync
46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/em-synchrony.rb', line 46 def self.sync(df) f = Fiber.current xback = proc {|r| if f == Fiber.current return r else f.resume r end } df.callback &xback df.errback &xback Fiber.yield end |