ruby-timeout-safe is a Ruby library that provides a safe and reliable timeout functionality for executing Ruby blocks. It uses Ruby's threading and monotonic time to ensure that timeouts are enforced even in the presence of blocking operations or long-running computations.
- Defines a
RubyTimeoutSafemodule with atimeoutmethod that executes a given Ruby block with a specified timeout duration. - If the block execution exceeds the timeout, a
TimeoutErrorexception is raised. - Supports handling large timeout values.
- Raises an
ArgumentErrorif a negative timeout value is provided.
Add this line to your application's Gemfile:
gem 'ruby_timeout_safe'require 'ruby_timeout_safe'
# Execute a block with a 2-second timeout
RubyTimeoutSafe.timeout(2) do
# Your code here
sleep 1 # This will not raise a timeout error
# ...
end
# Handling a timeout error
begin
RubyTimeoutSafe.timeout(1) do
# Your code here
sleep 3 # This will raise a TimeoutError
end
rescue Timeout::Error => e
puts "Execution timed out: #{e.message}"
endThis implementation uses Ruby's built-in threading and monotonic time functions. While it is more compatible with different Ruby implementations and platforms than a C extension, it may still have limitations based on Ruby's threading model.
After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests.
To install this gem onto your local machine, run bundle exec rake install.
Bug reports and pull requests are welcome on GitHub at https://github.com/sebyx07/ruby-timeout-safe. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.
The gem is available as open source under the terms of the MIT License.
Everyone interacting in the ruby-timeout-safe project's codebases, issue trackers, chat rooms, and mailing lists is expected to follow the code of conduct.