Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method · added in Ruby 3.2

IO#timeout=

timeout = duration → duration
timeout = nil → nil

Set the internal timeout to the specified duration or nil. The timeout applies to all blocking operations where possible.

This affects the following methods (but is not limited to): gets, puts, read, write, wait_readable and wait_writable. This also affects blocking socket operations like Socket#accept and Socket#connect.

Some operations like File#open and IO#close are not affected by the timeout. A timeout during a write operation may leave the IO in an inconsistent state, e.g. data was partially written. Generally speaking, a timeout is a last ditch effort to prevent an application from hanging on slow I/O operations, such as those that occur during a slowloris attack.

Ruby version changes

  1. 3.2
    • Introduce IO#timeout= and IO#timeout which can cause IO::TimeoutError to be raised if a blocking operation exceeds the specified timeout. [Feature #18630]

      Example
      STDIN.timeout = 1
      STDIN.read # => Blocking operation timed out! (IO::TimeoutError)
      
See also #timeout #to_i #tell #to_io also in 4.1 · 4.0 · 3.4 · 3.3