Cover by Leonard Richardson, Lucas Carlson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

3.13. Waiting a Certain Amount of Time

Problem

You want to pause your program, or a single thread of it, for a specific amount of time.

Solution

The Kernel#sleep method takes a floating-point number and puts the current thread to sleep for some (possibly fractional) number of seconds:

	3.downto(1) { |i| puts "#{i}…"; sleep(1) }; puts "Go!"
	# 3…
	# 2…
	# 1…
	# Go!

	Time.new                     # => Sat Mar 18 21:17:58 EST 2006
	sleep(10)
	Time.new                     # => Sat Mar 18 21:18:08 EST 2006
	sleep(1)
	Time.new                     # => Sat Mar 18 21:18:09 EST 2006
	# Sleep for less then a second.
	Time.new.usec                # => 377185
	sleep(0.1)
	Time.new.usec                # => 479230

Discussion

Timers are often used when a program needs to interact with a source much slower than a computer's CPU: a network pipe, or human eyes and hands. Rather than constantly poll for new data, a Ruby program can sleep for a fraction of a second between each poll, giving other programs on the CPU a chance to run. That's not much time by human standards, but sleeping for a fraction of a second at a time can greatly improve a system's overall performance.

You can pass any floating-point number to sleep, but that gives an exaggerated picture of how finely you can control a thread's sleeping time. For instance, you can't sleep for 10-50 seconds, because it's physically impossible (that's less than the Planck time). You can't sleep for Float::EPSILON seconds, because that's almost certainly less than the resolution of your computer's timer.

You probably can't even reliably sleep for a microsecond, ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required