我正在使用这样的 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
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
但你确定你的控制器是最好的地方吗?他们在后台任务中不会更好吗?