Ruby Event Machine 停止或终止延迟操作

标签 ruby eventmachine

我想知道是否可以停止执行已推迟的操作。

require 'rubygems'
require 'em-websocket'

EM.run do
  EM::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |ws|
     ws.onmessage do |msg|
       op = proc do
         sleep 5 # Thread safe IO here that is safely killed
         true
       end

      callback = proc do |result|
         puts "Done!"
      end

      EM.defer(op, callback)
    end
  end
end

这是一个示例网络套接字服务器。有时,当我收到一条消息时,我想做一些 IO,稍后可能会收到另一条消息,需要读取相同的内容,下一个总是优先于前一个。所以我想取消第一个操作并执行第二个操作。

最佳答案

这是我的解决方案。它类似于 EM.queue 解决方案,但只是使用哈希。

require 'rubygems'
require 'em-websocket'
require 'json'

EM.run do
  EM::WebSocket.start(:host => '0.0.0.0', :port => 3333) do |ws|
    mutex = Mutex.new # to make thread safe. See https://github.com/eventmachine/eventmachine/blob/master/lib/eventmachine.rb#L981
    queue = EM::Queue.new
    ws.onmessage do |msg|
      message_type = JSON.parse(msg)["type"]
      op = proc do
        mutex.synchronize do
          if message_type == "preferred"
            puts "killing non preferred\n"
            queue.size.times { queue.pop {|thread| thread.kill } }
          end
          queue << Thread.current
        end

        puts "doing the long running process"
        sleep 15 # Thread safe IO here that is safely killed
        true
      end

      callback = proc do |result|
        puts "Finished #{message_type} #{msg}"
      end

      EM.defer(op, callback)
    end
  end
end

关于Ruby Event Machine 停止或终止延迟操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19172707/

相关文章:

ruby - 如何编写 'unless'语句

ruby-on-rails - Rails - 查找用户的所有项目

Ruby 处理数千个异步请求的最佳方式?

ruby - 无法启动 sinatra 进程 - eventmachine "no acceptor"

ruby - Date、Time 和 DateTime 类是否必需?

ruby - 为 PostgreSQL 8.3 安装 PL/Ruby

sql - 如何为另一个属性的任何给定值选择具有最大值的属性的每个模型?

ruby - 使用 Mechanize 的异步请求

ruby - $&、$'、$1 等在 Ruby 代码中是什么意思?

c# - POCO 1.5.1 Websocket 客户端无法连接到 c# websocket 服务器