Tell Ruby Program to Wait some amount of time

眉间皱痕 提交于 2019-11-30 05:53:57

问题


How do you tell a Ruby program to wait an arbitrary amount of time before moving on to the next line of code?


回答1:


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



回答2:


Use sleep like so:

sleep 2

That'll sleep for 2 seconds.

Be careful to give an argument. If you just run sleep, the process will sleep forever. (This is useful when you want a thread to sleep until it's woken.)




回答3:


I find until very useful with sleep. example:

> time = Time.now
> sleep 2.seconds until Time.now > time + 10.seconds # breaks when true



回答4:


sleep 6 will sleep for 6 seconds. For a longer duration, you can also use sleep(6.minutes) or sleep(6.hours).



来源:https://stackoverflow.com/questions/1329967/tell-ruby-program-to-wait-some-amount-of-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!