你应该看看Ruby的Timeout.
来自文档:
require 'timeout'
status = Timeout::timeout(5) {
# Something that should be interrupted if it takes too much time...
}
Run Code Online (Sandbox Code Playgroud)
我认为上面的 Timeout 方法可能是解决这个问题的最优雅的方法。大多数语言中可用的另一种解决方案是使用select. 您传递要监视的文件描述符列表和可选的超时。代码不太简洁:
ready_fds = select [ $stdin ], [], [], 10
puts ready_fds.first.first.gets unless ready_fds.nil?
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1039 次 |
| 最近记录: |