user4493605
user4493605

Reputation: 391

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.

Upvotes: 1

Views: 612

Answers (2)

Matt
Matt

Reputation: 74630

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

Upvotes: 4

sawa
sawa

Reputation: 168081

require "timeout"

Timeout.timeout(x) do
  s = gets
  ...
end

Upvotes: 0

Related Questions