Skip to content

Instantly share code, notes, and snippets.

@axelabs
Created March 19, 2015 15:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axelabs/d01e5c7c598d497869f8 to your computer and use it in GitHub Desktop.
Save axelabs/d01e5c7c598d497869f8 to your computer and use it in GitHub Desktop.
Unblocking EventMachine's deferred callbacks
#!/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
@axelabs
Copy link
Author

axelabs commented Mar 19, 2015

Copy link

ghost commented Mar 19, 2015

A good example is processing an http callback unBlock'ed:

slow = URI("http://httpbin.org/delay/5")
http = EventMachine::HttpRequest.new(slow).get
procEssHTTP = proc { puts "1";sleep 2; puts "3" }
http.callback &unBlock {procEssHTTP.call}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment