Sha256: d610ba7e5265fff8b82349dac035cd2d13f9698213bdec263350c59554b71ac8

Contents?: true

Size: 975 Bytes

Versions: 2

Compression:

Stored size: 975 Bytes

Contents

# frozen_string_literal: true

class Async::Timer
  attr_reader :dealay, :repeat

  class Error < StandardError; end

  class AlreadyStarted < Error; end

  def initialize(delay, repeat: true, start: true, run_on_start: false, parent: Async::Task.current, &block)
    raise ArgumentError, "Block must be given" if block.nil?

    @delay = delay
    @repeat = repeat
    @run_on_start = run_on_start
    @parent = parent
    @block = block

    self.start if start
  end

  def stop = @task.stop
  def call = @block.call

  def active? = @active

  def restart
    stop
    @task.wait
    start
  end

  def start(run: false)
    raise AlreadyStarted, "Timer already started" if active?

    @active = true

    @task = @parent.async do
      call if @run_on_start || run

      loop do
        sleep(@delay)
        call
        break unless @repeat
      rescue Async::Stop, Async::TimeoutError
        break
      ensure
        @active = false
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
async-tools-0.1.6 lib/async/timer.rb
async-tools-0.1.5 lib/async/timer.rb