Created
March 19, 2015 15:34
-
-
Save axelabs/d01e5c7c598d497869f8 to your computer and use it in GitHub Desktop.
Unblocking EventMachine's deferred callbacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
# Example of how to unblock EventMachine's deffered callbacks | |
# Based on http://stackoverflow.com/a/11778588/632827 | |
# For output example see: http://goo.gl/d6E9E0 | |
require 'eventmachine' | |
iam = [ 'blocking', 'non-blocking' ] | |
def unBlock &blocking | |
proc { EM.defer(blocking) } | |
end | |
work = proc { | |
puts "[#{Time.now}] I'm a blocking worker, I'll be done in 2 secs" | |
sleep 2 | |
puts "[#{Time.now}] worker done!" | |
} | |
callback = proc { | |
puts "[#{Time.now}] I'm a %s callback, I'll be done in 4 secs" % iam.shift | |
sleep 4 | |
puts "[#{Time.now}] callback done!" | |
} | |
EM.run do | |
EM.add_periodic_timer(1) { puts "[#{Time.now}] ." } | |
EM.defer(work, callback ) | |
# Lets do the same thing in a bit but unblocked | |
EM.add_timer(7) { | |
EM.defer(work, unBlock {callback.call} ) | |
} | |
EM.add_timer(15) { puts "[#{Time.now}] Bye!"; EM.stop } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A good example is processing an http callback unBlock'ed: