Kernel#sleep

sleep([duration]) -> integer or nil
Returns: Integer (seconds) or nil · Updated March 13, 2026 · Kernel Methods
timing threads sleep execution

Kernel#sleep suspends the current thread’s execution for the specified number of seconds. If no duration is given, it sleeps indefinitely until interrupted. Returns the number of seconds actually slept, or nil if interrupted by a signal.

Syntax

sleep(duration)
sleep

Parameters

ParameterTypeDefaultDescription
durationNumericnilNumber of seconds to sleep. Can be fractional for sub-second precision. If nil or omitted, sleeps indefinitely.

Examples

Basic usage

puts "Starting"
sleep(2)
puts "Woke up after 2 seconds"
# Starting
# Woke up after 2 seconds

Sleeping for fractional seconds

start = Time.now
sleep(0.5)  # sleep for 500 milliseconds
puts Time.now - start
# => 0.5

Sleeping indefinitely

# This runs until interrupted
sleep

Using sleep in a loop

5.times do |i|
  puts "Count: #{i}"
  sleep(1)
end
# Count: 0
# Count: 1
# Count: 2
# Count: 3
# Count: 4

Common Patterns

Polling interval

def poll_until(condition, interval: 1, timeout: 30)
  elapsed = 0
  while elapsed < timeout
    return yield if yield
    sleep(interval)
    elapsed += interval
  end
  nil
end

# Usage: wait for a file to exist
poll_until { File.exist?('/tmp/ready') }

Rate limiting

requests = ['req1', 'req2', 'req3']

requests.each do |req|
  process(req)
  sleep(0.5)  # rate limit to 2 requests per second
end

Retry with backoff

def retry_with_backoff(max_attempts: 3)
  attempt = 0
  begin
    attempt += 1
    yield
  rescue => e
    if attempt < max_attempts
      sleep(2 ** attempt)  # 2, 4, 8 seconds
      retry
    else
      raise e
    end
  end
end

Errors

  • ArgumentError: Raised if duration is negative.
  • ThreadError: May be raised if sleeping while the thread is being killed.

See Also