How to set timeout in Ruby?

Ruby provides a handy tool called the Timeout module, which lets you set limits on how long tasks can take to execute. This article focuses on discussing the ways to set the timeout in Ruby.

Syntax:

require ‘timeout’
begin
Timeout.timeout(seconds) do
# Code block to be executed within the timeout
end
rescue Timeout::Error
# Code to handle timeout
end

Explanation:

  1. require ‘timeout’: This ensures that the Timeout module is available for use.
  2. Timeout.timeout(seconds): This sets a timeout for the specified number of seconds.
  3. The code block within the do and end keywords represents the task to be executed within the timeout.
  4. rescue Timeout::Error: This catches any Timeout::Error that occurs if the task exceeds the specified timeout duration.
  5. You can replace seconds with the desired timeout duration in seconds.

Example 1:

Below is the Ruby program to implement the timeout:

Ruby
require 'timeout'

begin
  Timeout.timeout(5) do
    # Simulate a long-running operation
    sleep 10
    puts "Task completed successfully within the timeout"
  end
rescue Timeout::Error
  puts "Task timed out! It took longer than expected."
end

In the above example:

If the operation completes within the 5-second timeout, the output will be

Output

If the operation takes longer than 5 seconds and times out, the output will be:

Output

Explanation:

  1. We require the timeout module at the beginning of our script.
  2. We set a timeout of 5 seconds using Timeout.timeout(5).
  3. Inside the block, we simulate a long-running operation with sleep 10.
  4. If the operation takes longer than 5 seconds, a Timeout::Error is raised, and we handle it by printing a message indicating that the task timed out.
  5. If the operation completes within 5 seconds, we print a message confirming successful completion within the timeout.

Example 2:

Below is the Ruby program to implement the timeout:

Ruby
require 'timeout'

begin
  Timeout.timeout(3) do
    # Simulate a potentially infinite loop
    loop do
      puts "Loop iteration"
      sleep 1
    end
  end
rescue Timeout::Error
  puts "Task timed out! Exiting loop."
end

Output:

Since each iteration of the loop takes 1 second, approximately 3 iterations will be completed before the timeout is reached.

Output

Explanation:

  1. A timeout of 3 seconds is set for a loop that continuously prints “Loop iteration” with a 1-second delay between iterations.
  2. If the loop doesn’t complete within 3 seconds, a Timeout::Error is raised, and the rescue block prints “Task timed out! Exiting loop.” Otherwise, if the loop completes within the timeout, it prints each iteration until completion.

Conclusion

In conclusion, we’ve learned to use Ruby’s Timeout module to limit task execution times, ensuring application responsiveness even during lengthy operations. Timeouts are essential for maintaining stability and preventing delays, particularly in network requests or database queries.