ccy
ccy

Reputation: 1415

sleep until condition is true in 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

Upvotes: 19

Views: 29393

Answers (5)

user513951
user513951

Reputation: 13612

Here's an option that works well with longer conditionals:

sleep 1 until begin
  do_stuff
  do_more_stuff
  check_condition
end

Upvotes: 0

dansalmo
dansalmo

Reputation: 11686

I like this form since it is simple and only uses sleep if needed after it tests for the done condition:

begin
  ready_to_go = do_some_action
end until ready_to_go or not sleep 1

Upvotes: 0

Jonas
Jonas

Reputation: 5149

def sleep_until(time)
  time.times do
    break if block_given? && yield
    sleep(1)
  end
end

Usage:

sleep_until(18){till_i_die}

Upvotes: 1

mikhail_b
mikhail_b

Reputation: 970

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

Upvotes: 3

the Tin Man
the Tin Man

Reputation: 160551

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

Upvotes: 26

Related Questions