How to put a delay on a loop in Ruby?

前端 未结 2 1650
情书的邮戳
情书的邮戳 2020-12-31 08:32

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?

2条回答
  •  天命终不由人
    2020-12-31 08:53

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

    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
    

提交回复
热议问题