如何在 Ruby 中延迟循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28240510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:41:13  来源:igfitidea点击:

How to put a delay on a loop in Ruby?

rubyloops

提问by Salviati

For example, if I want to make a timer, how do I make a delay in the loop so it counts in seconds and do not just loop through it in a millisecond?

例如,如果我想制作一个计时器,我如何在循环中进行延迟,使其以秒为单位计数,而不仅仅是以毫秒为单位进行循环?

回答by Phrogz

The 'comment' above is your answer, given the very simple direct question you have asked:

鉴于您提出的非常简单的直接问题,上面的“评论”就是您的答案:

1.upto(5) do |n|
  puts n
  sleep 1 # second
end

It may be that you want to run a method periodically, without blocking the rest of your code. In this case, you want to use a Thread (and possibly create a mutex to ensure that two pieces of code are not attempting to modify the same data structure at the same time):

您可能希望定期运行一个方法,而不阻塞其余代码。在这种情况下,您希望使用 Thread(并可能创建一个互斥锁以确保两段代码不会同时尝试修改相同的数据结构):

require 'thread'

items = []
one_at_a_time = Mutex.new

# Show the values every 5 seconds
Thread.new do
  loop do
    one_at_a_time.synchronize do
      puts "Items are now: #{items.inspect}"
      sleep 5
    end
  end
end

1000.times do
  one_at_a_time.synchronize do
    new_items = fetch_items_from_web
    a.concat( new_items )
  end
end

回答by sawa

Somehow, many people think that putting a sleepmethod with a constant time interval as its argument will work. However, note that no method takes zero time. If you put sleep(1)within a loop, the cycle will surely be more than 1second as long as you have some other content in the loop. What is worse, it does not always take the same time processing each iteration of a loop. Each cycle will take more than 1second, with the error being random. As the loop keeps running, this error will contaminate and grow always toward positive. Especially if you want a timer, where the cycle is important, you do not want to do that.

不知何故,许多人认为将一个sleep具有恒定时间间隔的方法作为其参数会起作用。但是,请注意,没有任何方法需要零时间。如果您放入sleep(1)循环中,1只要循环中还有其他内容,循环肯定会超过一秒。更糟糕的是,处理循环的每次迭代并不总是花费相同的时间。每个周期将花费超过1一秒的时间,错误是随机的。随着循环不断运行,此错误将受到污染并始终朝着正值增长。特别是如果您想要一个计时器,其中周期很重要,您不想这样做。

The correct way to loop with constant specified time interval is to do it like this:

以恒定的指定时间间隔循环的正确方法是这样做:

loop do
  t = Time.now
    #... content of the loop
  sleep(t + 1 - Time.now)
end