sleep until condition is true in ruby

后端 未结 4 1660
盖世英雄少女心
盖世英雄少女心 2021-02-05 11:12

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
4条回答
  •  梦毁少年i
    2021-02-05 11:34

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

提交回复
热议问题