Sleep Until Condition Is True in Ruby

sleep until condition is true in ruby

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

Can opscode chef perform wait until a condition becomes true?

It's actually a pattern I've seen from time to time in various cookbooks, often used to wait for a block device or to mount something, or to wait for a cloud resource. For the wait cookbook you've found, I had to dig up the actual source repo on Github to figure out how to use it. Here's an example:

until 'pigs fly' do
command '/bin/false'
wait_interval 5
message 'sleeping for 5 seconds and retrying'
action :run
end

It appears to call ruby's system(command) and sleep(wait_interval). Hope this helps!

EDIT: As other posters have stated, if you can do the whole thing in chef, a notification with a directory resource and delete action is a better solution. But you asked how to use the wait resource, so I wanted to answer that specifically.

Tell Ruby Program to Wait some amount of time

Like this:

sleep(num_secs)

The num_secs value can be an integer or float.

Also, if you're writing this within a Rails app, or have included the ActiveSupport library in your project, you can construct longer intervals using the following convenience syntax:

sleep(4.minutes)
# or, even longer...
sleep(2.hours); sleep(3.days) # etc., etc.
# or shorter
sleep(0.5) # half a second

Pause an until loop and wait for a keypress to continue (Ruby)

The easy solution would be to add a gets before flip. Then it would wait for you to hit enter.

If you really want to wait for spacebar, you can use curses. It can do robust input handling in the terminal, but it can get pretty complicated. If you're using Ruby 2.1.0 or earlier curses is part of the stdlib. Otherwise you'll need one of the gems.



Related Topics



Leave a reply



Submit