user4493605 user4493605 - 7 months ago 17
Ruby Question

Timeout if no user input for `x` seconds

How would I program a chunk of code in Ruby, which would timeout or exit if no user input is entered for

x
amount of time?

I don't have a half completed script too better convey my question, or even a pseudo-code concept algorithm.

Answer

You can use the Timeout module that is included in the standard libraries. It will raise a Timeout::Error on timeout if you want to rescue it.

require 'timeout'
x = 10
begin
  status = Timeout::timeout(x) {
    printf "Input: "
    gets
  }
  puts "Got: #{status}"
rescue Timeout::Error
  puts "Input timed out after #{x} seconds"
end
Comments