Sha256: 765f2ee360e2ed794508f5564e3182b367073f1235c8455a5e1ac65dd051428a

Contents?: true

Size: 908 Bytes

Versions: 3

Compression:

Stored size: 908 Bytes

Contents

class Clock
  attr_accessor :persistent

  def initialize(&block)
    @block = block
    @thread = nil
    @persistent = false # if persistent, clock is not stopped when loading new scene

    Global.clocks << self
  end

  def run_now
    @thread =
      Thread.new do
        @block.call
      end
  end

  def run_on(seconds:)
    @thread =
      Thread.new do
        sleep(seconds)
        @block.call
      end
  end

  def repeat(seconds: 1, times: Float::INFINITY)
    times_executed = 0
    @thread =
      Thread.new do
        while(times_executed < times)
          @block.call
          times_executed += 1;

          seconds_to_sleep = seconds.is_a?(Range) ? rand(seconds) : seconds
          sleep(seconds_to_sleep)
        end
      end
  end

  def stop
    Thread.kill(@thread) unless @thread.nil?
  end

  def started?
    !@thread.nil?
  end

  def persistent?
    @persistent
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
fantasy-0.1.5.1 lib/fantasy/clock.rb
fantasy-0.1.5 lib/fantasy/clock.rb
fantasy-0.1.3 lib/fantasy/clock.rb