Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sleep until condition is true in ruby

Tags:

ruby

Is there any better way in Ruby to sleep until some condition is true ?

loop do 
  sleep(1)
  if ready_to_go
    break
  end
end
like image 389
ccy Avatar asked Feb 12 '11 01:02

ccy


People also ask

What is until in Ruby?

until: This is the ruby predefined keyword which will be used for the execution of the same piece of code again and again, it indicates the start of any loop.

What is sleep method in Ruby?

Ruby sleep() method sleep() method accepts number of seconds as argument and suspends the thread of execution for the amount of seconds being passed as parameter. The parameter can be passed as number or float or fraction. If you are working with Ruby on Rails, then you get the facility to pass parameter with .

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

How do you stop 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

until can be a statement modifier, leading to:

sleep(1) until ready_to_go

You'll have to use that in a thread with another thread changing ready_to_go otherwise you'll hang.

while (!ready_to_go)
  sleep(1)
end

is similar to that but, again, you'd need something to toggle ready_to_go or you'd hang.

You could use:

until (ready_to_go)
  sleep(1)
end

but I've never been comfortable using until like that. Actually I almost never use it, preferring the equivalent (!ready_to_go).

like image 124
the Tin Man Avatar answered Sep 23 '22 15:09

the Tin Man


You can use the waitutil gem as described at http://rubytools.github.io/waitutil/, e.g.

require 'waitutil'

WaitUtil.wait_for_condition("my_event to happen", 
                            :timeout_sec => 30,
                            :delay_sec => 0.5) do
  check_if_my_event_happened
end
like image 42
mikhail_b Avatar answered Sep 20 '22 15:09

mikhail_b