当前位置 : 主页 > 编程语言 > ruby >

ruby-on-rails – 如果超过X秒,则退出线程

来源:互联网 收集:自由互联 发布时间:2021-06-23
我正在使用这样的 Ruby线程: threads = []for page in pages threads Thread.new(page) { |myPage| h = Net::HTTP.new(myPage, 80) puts "Fetching: #{myPage}" resp, data = h.get('/', nil ) puts "Got #{myPage}: #{resp.message}" }endthread
我正在使用这样的 Ruby线程:

threads = []

for page in pages
  threads << Thread.new(page) { |myPage|

    h = Net::HTTP.new(myPage, 80)
    puts "Fetching: #{myPage}"
    resp, data = h.get('/', nil )
    puts "Got #{myPage}:  #{resp.message}"
  }
end

threads.each { |aThread|  aThread.join }

假设我想杀死一分钟后仍在运行的所有线程.我该怎么做?

我通常用 Timeout超时操作:

require "timeout"
Timeout.timeout(seconds) do
 ...
end

也许this可以提供帮助,所以在你的情况下,我认为这样的事情应该有效:

begin
  Timeout.timeout(5) do
    for page in pages
      threads << Thread.new(page) { |myPage|

        h = Net::HTTP.new(myPage, 80)
        puts "Fetching: #{myPage}"
        resp, data = h.get('/', nil )
        puts "Got #{myPage}:  #{resp.message}"
      }
    end
    threads.each { |aThread|  aThread.join }
  end
rescue Timeout::Error
   # kill threads here
end

但你确定你的控制器是最好的地方吗?他们在后台任务中不会更好吗?

网友评论