Timers in Ruby

We often want to execute code at some point in the future, or repeatedly at some interval. Ruby provides timer features that make both of these tasks easy. We’ll look at timers in this example.

require 'timers'

# Create a new Timers instance
timers = Timers::Group.new

# Timers represent a single event in the future. You
# tell the timer how long you want to wait, and it
# will execute the given block at that time.
# This timer will wait 2 seconds.
timer1 = timers.after(2) do
  puts "Timer 1 fired"
end

# The `wait` method blocks until the timer fires.
timers.wait

# If you just wanted to wait, you could have used
# `sleep`. One reason a timer may be useful is
# that you can cancel the timer before it fires.
# Here's an example of that.
timer2 = timers.after(1) do
  puts "Timer 2 fired"
end

# Start the timer in a separate thread
Thread.new do
  timers.wait
end

# Cancel the timer
timer2.cancel
puts "Timer 2 stopped"

# Give the `timer2` enough time to fire, if it ever
# was going to, to show it is in fact stopped.
sleep 2

To run this program:

$ ruby timers.rb
Timer 1 fired
Timer 2 stopped

The first timer will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire.

Note that in this Ruby version, we’re using the timers gem, which provides a more flexible and powerful timer implementation than Ruby’s built-in sleep method. You’ll need to install this gem with gem install timers before running the program.

In Ruby, we don’t have the concept of channels like in Go, so we’ve adapted the example to use threads and the Timers::Group class to achieve similar functionality.