在尝试使用事件机和可延迟的简单示例时,我无法使代码按预期工作。我期望在Worker上调用工作时,以下代码不会阻塞,并且在向服务器发送两个连续的消息之后,客户端将在第一个Worker运行完之前收到两个“ Job Scheduled”通知。如果我显式创建一个线程而不是EM.spawn,它将按预期工作。如何使它在eventmachine中工作?
class Worker
include EM::Deferrable
def work
3.times do |i|
sleep 1
end
set_deferred_status :succeeded
end
end
module Handler
def receive_data(message)
EM.spawn do
worker = Worker.new
worker.callback { puts "Finished" }
worker.work
end.notify
send_data("Job Scheduled...")
end
end
EventMachine::run do
EventMachine::start_server "localhost", 8081, Handler
puts 'running server on 8081'
end
谢谢!