Created
August 5, 2012 20:15
-
-
Save phillbaker/3266978 to your computer and use it in GitHub Desktop.
EventMachine Cheat Sheet
This file contains hidden or 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
EventMachine | |
============ | |
Installation: | |
$ gem install eventmachine | |
Synchronous Ruby code (Not EM appropriate): | |
ret = operation(); do_something_with(ret) | |
Evented, asynchronous code (EM appropriate): | |
operation{ |ret| do_something_with(ret) } | |
Start the reactor: | |
EM.run {...} | EventMachine.run do ... end | |
Check that the reactor is running: | |
EM.reactor_running? | |
Start a server: | |
EM.run do | |
EM.start_server '0.0.0.0', 6666, FooServer | |
end | |
Stop the reactor: | |
EM.stop | EM.run{ puts "reactor started!"; EM.stop; }; puts "this will happen" | |
Queue a proc to be executed on the next iteration of the reactor loop: | |
EM.next_tick | do_work = proc{...}; EM.next_tick(&do_work) | |
Iterate over multiple ticks of the reactor: | |
EM::Iterator.new(0..10, 2).each(proc{ |num,iter| iter.next }, proc{ puts 'All done' }) | |
Set the size of the worker thread pool: | |
EM.threadpool_size | |
Push a job onto the thread pool: | |
EM.defer(proc{ result = long_blocking_call_on_worker_thread; result }, proc{|result| use_reactor_thread(result) }) | |
Schedule/defer something for specified seconds: | |
EventMachine.add_timer(1) { puts "hello one second from #{time}!" } | |
Create interval timing: | |
EM::PeriodicTimer.new(0.25) { foo_every_quarter_second() } | |
Specify event handlers: | |
operation{ do_something } | operation(proc{ do_something }) | operation(&method(:do_something)) | operation(obj.method(:do_something)) | |
Standard EM:Callback interface: | |
def operation(*args, &blk) { handler = EM::Callback(*args, &blk); handler.call } | |
EM.schedule | |
EM::Deferrable | |
EM::Queue | |
EM::Channel | |
EM.system | |
EM.start_server (and EM.stop_server): TCP Server | |
EM.connect (and EM.bind_connect): TCP Client | |
EM.open_datagram_socket: UDP Socket | |
EM::Protocols | |
EM.watch and EM.attach | |
EM.watch_file | |
EM.watch_process | |
EM.open_keyboard |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment