告诉 Ruby 程序等待一段时间
如何告诉 Ruby 程序在继续执行下一行代码之前等待任意时间?
How do you tell a Ruby program to wait an arbitrary amount of time before moving on to the next line of code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
像这样:
num_secs
值可以是整数或浮点数。另外,如果您在 Rails 应用程序中编写此代码,或者已在项目中包含 ActiveSupport 库,则可以使用以下便捷语法构造更长的间隔:
Like this:
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 :
这将休眠 2 秒。
小心地提出论点。如果您只是运行
sleep
,该进程将永远休眠。 (当您希望线程休眠直到被唤醒时,这非常有用。)Use sleep like so:
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.)我发现
until
对于睡眠非常有用。例子:I find
until
very useful with sleep. example:像这样
sleep(no_of_seconds)
或者您可以传递其他可能的参数,例如:
sleep(5.seconds)
sleep(5.minutes)
睡眠(5.小时)
睡眠(5.天)
Like this
sleep(no_of_seconds)
Or you may pass other possible arguments like:
sleep(5.seconds)
sleep(5.minutes)
sleep(5.hours)
sleep(5.days)
秒/分钟/小时的实现,这是rails方法。请注意,隐式返回不是必需的,但它们看起来更干净,所以我更喜欢它们。我不确定 Rails 是否有 .days 或者是否更进一步,但这些是我需要的。
之后,您可以执行以下操作:
sleep 5.seconds
睡眠 5 秒。您可以sleep 5.mines
来睡5分钟。您可以sleep 5.hours
来睡5个小时。最后,您可以执行sleep 5.days
来睡眠 5 天...您可以添加任何返回 self * 值(该时间范围内的秒数)的方法。作为练习,尝试实施几个月!
Implementation of seconds/minutes/hours, which are rails methods. Note that implicit returns aren't needed, but they look cleaner, so I prefer them. I'm not sure Rails even has .days or if it goes further, but these are the ones I need.
After this, you can do:
sleep 5.seconds
to sleep for 5 seconds. You can dosleep 5.minutes
to sleep for 5 min. You can dosleep 5.hours
to sleep for 5 hours. And finally, you can dosleep 5.days
to sleep for 5 days... You can add any method that return the value of self * (amount of seconds in that timeframe).As an exercise, try implementing it for months!
sleep 6
将休眠 6 秒。如果需要更长的持续时间,您还可以使用sleep(6.minutes)
或sleep(6.hours)
。sleep 6
will sleep for 6 seconds. For a longer duration, you can also usesleep(6.minutes)
orsleep(6.hours)
.的示例。
这是使用
sleep
和sidekiq
sleep 10 秒并打印出"Working super hard"
This is an example of using
sleep
withsidekiq
sleep for 10 seconds and print out
"Working super hard"
.