如何在Ruby中延迟循环? [英] How to put a delay on a loop in Ruby?

查看:130
本文介绍了如何在Ruby中延迟循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我想创建一个计时器,该如何在循环中进行延迟,使它以秒为单位计数,而不仅仅是在毫秒内循环遍历?

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?

推荐答案

鉴于您所问的非常简单的直接问题,上面的评论"是您的答案:

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

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

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):

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

这篇关于如何在Ruby中延迟循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆