Sha256: 05d95a18dccb2248c98142e8e28b3e56fade841abbf976e0fc0392d33eabfdea

Contents?: true

Size: 1.33 KB

Versions: 8

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true

class Async::Timer
  attr_reader :dealay, :repeat

  class Error < StandardError; end

  class AlreadyStarted < Error; end

  def initialize(delay, # rubocop:disable Metrics/CyclomaticComplexity,Metrics/ParameterLists
                 repeat: true,
                 start: true,
                 run_on_start: false,
                 call: nil,
                 on_error: nil,
                 parent: Async::Task.current, &block)
    callables = [call, block]
    raise ArgumentError, "either block or call: must be given" if callables.all?(&:nil?) || callables.none?(&:nil?)

    @delay = delay
    @repeat = repeat
    @run_on_start = run_on_start
    @callable = call || block
    @on_error = on_error || ->(e) { raise e }
    @parent = parent

    self.start if start
  end

  def stop = @task.stop
  def call = @callable.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
      rescued_call if @run_on_start || run

      loop do
        sleep(@delay)
        rescued_call
        break unless @repeat
      ensure
        @active = false
      end
    end
  end

  def rescued_call
    call
  rescue StandardError => e
    @on_error.call(e)
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
async-tools-0.2.8 lib/async/timer.rb
async-tools-0.2.7 lib/async/timer.rb
async-tools-0.2.6 lib/async/timer.rb
async-tools-0.2.5 lib/async/timer.rb
async-tools-0.2.4 lib/async/timer.rb
async-tools-0.2.2 lib/async/timer.rb
async-tools-0.2.1 lib/async/timer.rb
async-tools-0.1.10 lib/async/timer.rb