Tickers in Ruby

Our example demonstrates how to use periodic timers in Ruby. While Go has built-in tickers, Ruby doesn’t have an exact equivalent, but we can achieve similar functionality using threads and loops.

require 'time'

# Create a method to simulate a ticker
def create_ticker(interval)
  Thread.new do
    loop do
      yield Time.now
      sleep interval
    end
  end
end

# Create a method to stop the ticker
def stop_ticker(ticker, duration)
  Thread.new do
    sleep duration
    ticker.kill
    puts "Ticker stopped"
  end
end

# Main execution
ticker = create_ticker(0.5) do |time|
  puts "Tick at #{time}"
end

# Stop the ticker after 1.6 seconds
stop_ticker(ticker, 1.6)

# Wait for both threads to finish
ticker.join

In this Ruby program:

  1. We define a create_ticker method that simulates a ticker using a loop in a separate thread. It yields the current time at each interval.

  2. The stop_ticker method is created to stop the ticker after a specified duration.

  3. In the main execution, we create a ticker that ticks every 0.5 seconds (500 milliseconds) and prints the current time.

  4. We set up the ticker to stop after 1.6 seconds.

  5. The program waits for both threads to finish execution.

When we run this program, the ticker should tick 3 times before we stop it:

$ ruby tickers.rb
Tick at 2023-06-01 12:34:56 +0000
Tick at 2023-06-01 12:34:56 +0000
Tick at 2023-06-01 12:34:57 +0000
Ticker stopped

This example demonstrates how to create a simple periodic timer in Ruby. While it doesn’t use the exact same mechanisms as Go’s tickers, it achieves similar functionality using Ruby’s threading capabilities.