Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a delay on a loop in Ruby?

Tags:

loops

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?

like image 212
Salviati Avatar asked Jan 30 '15 16:01

Salviati


People also ask

How do you add a timer in Ruby?

Here's 3 simple steps: 1) write down current time as start time; 2) every second (or so) compare current time with start time; 3) if specified number of seconds have passed since start time, ring the bell.

How do you skip iterations in Ruby?

skip to the next iteration while part way through the current interation – this is done using the “next” keyword. exit the loop early – this is done using the “break” keyword. redo the current iteration – this is done using the “redo” keyword.

How do you break a while loop in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.


2 Answers

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
like image 75
Phrogz Avatar answered Nov 04 '22 07:11

Phrogz


Somehow, many people think that putting a sleep method 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 1 second 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 1 second, 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.

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
like image 14
sawa Avatar answered Nov 04 '22 07:11

sawa