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.
To run this program:
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.