Sha256: 5fc174205f052217a2ec0f21eacf823eac4923177f29c837983d67ed4677264a

Contents?: true

Size: 924 Bytes

Versions: 3

Compression:

Stored size: 924 Bytes

Contents

# frozen_string_literal: true

class Async::Timer
  extend Forwardable

  attr_reader :dealay, :repeat

  class Error < StandardError; end

  class AlreadyStarted < Error; end

  def initialize(delay, repeat: true, parent: Async::Task.current, &block)
    @delay = delay
    @repeat = repeat
    @parent = parent
    @block = block

    start
  end

  def_delegator :@task, :stop
  def_delegator :@block, :call, :execute

  def active?
    @active
  end

  def restart
    stop
    @task.wait
    start
  end

  def schedule
    @parent.async do
      execute
    end
  end

  private

  def start
    raise AlreadyStarted, "Timer already started" if active?

    @active = true

    @task = @parent.async do
      loop do
        @parent.sleep(@delay)
        schedule
        break unless @repeat
      rescue Async::Stop, Async::TimeoutError
        break
      ensure
        @active = false
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
async-tools-0.1.2 lib/async/timer.rb
async-tools-0.1.1 lib/async/timer.rb
async-tools-0.1.0 lib/async/timer.rb