Sha256: 8132a37761de66c6fb649e1fcf415dd68f860e6fff686613b3a528c3283d4761

Contents?: true

Size: 1.2 KB

Versions: 4

Compression:

Stored size: 1.2 KB

Contents

# frozen_string_literal: true

module Lita
  # A timer that executes a block after a certain number of seconds, either once or repeatedly.
  # @since 3.0.0
  class Timer
    # @param interval [Integer] The number of seconds to wait before calling the block.
    # @param recurring [Boolean] If true, the timer will fire repeatedly until stopped.
    # @yieldparam timer [Timer] The current {Timer} instance.
    def initialize(interval: 0, recurring: false, &block)
      @interval = interval
      @recurring = recurring
      @running = false
      @block = block
    end

    # Starts running the timer.
    def start
      @running = true
      run
    end

    # Stops the timer, preventing any further invocations of the block until started again.
    def stop
      @running = false
    end

    private

    # Is this a recurring timer?
    def recurring?
      @recurring
    end

    # Sleep for the given interval, call the block, then run again if it's a recurring timer.
    def run
      loop do
        sleep @interval
        @block.call(self) if running? && @block
        break unless running? && recurring?
      end
    end

    # Is the timer currently running?
    def running?
      @running
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rita-5.0.0.alpha.4 lib/lita/timer.rb
rita-5.0.0.alpha.3 lib/lita/timer.rb
rita-5.0.0.alpha.2 lib/lita/timer.rb
rita-5.0.0.alpha.1 lib/lita/timer.rb