我正在创建一个后台脚本,该脚本使用 EventMachine 通过 WebSockets 连接到服务器。该脚本将使用 DelayedJob 或 Resque 运行。我已经能够让它与 WebSockets 服务器对话并发送消息,但是只要在 EventMachine 循环中引发错误,它就不会使脚本崩溃——这是应该发生的(以及我需要发生的) . 我不必使用 EventMachine,因为我只发送 WebSocket 消息而不接收它们 - 但我很想在这方面提供任何帮助 :) 谢谢!
#!/usr/bin/env ruby
require 'rubygems'
require 'eventmachine'
require 'em-http'
class Job
include EventMachine::Deferrable
def self.perform
job = Job.new
EventMachine.run {
http = EventMachine::HttpRequest.new("ws://localhost:8080/").get :timeout => 0
http.errback { puts "oops" }
http.callback {
puts "WebSocket connected!"
http.send("Hello watcher")
}
http.stream { |msg| }
job.callback { puts "done" }
Thread.new {
job.execute(http)
http.close
EventMachine.stop
}
}
end
def execute(h)
sleep 1
puts "Job Runner!"
h.send("welcome!")
sleep 2
asdsadsa # here I am trying to simulate an error
sleep 1
h.send("we are all done!")
sleep 1
set_deferred_status :succeeded
end
end
Job.perform