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
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.
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 .
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.
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.
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)
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With