Sha256: a50027e67ff0b87c8a4319ce7f1c63e6dbe8ef97bd4b4ea418d5cdc9249ee40a

Contents?: true

Size: 1020 Bytes

Versions: 4

Compression:

Stored size: 1020 Bytes

Contents

module BubbleWrap
  module Reactor
    # Creates a repeating timer.
    class PeriodicTimer
      include Eventable

      attr_accessor :interval

      # Create a new timer that fires after a given number of seconds
      def initialize(interval, *args, &blk)
        options = args.last.is_a?(Hash) ? args.last : {}
        callback = args.first.respond_to?(:call) ? args.first : blk
        raise ArgumentError, "No callback or block supplied to periodic timer" unless callback

        self.interval = interval
        fire = proc {
          callback.call
          trigger(:fired)
        }
        @timer = NSTimer.timerWithTimeInterval(interval, target: fire, selector: 'call:', userInfo: nil, repeats: true)
        runloop_mode = options[:common_modes] ? NSRunLoopCommonModes : NSDefaultRunLoopMode 
        NSRunLoop.currentRunLoop.addTimer(@timer, forMode: runloop_mode)
      end

      # Cancel the timer
      def cancel
        @timer.invalidate
        trigger(:cancelled)
      end

    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
bubble-wrap-1.3.0 motion/reactor/periodic_timer.rb
bubble-wrap-1.3.0.osx motion/reactor/periodic_timer.rb
bubble-wrap-1.2.0 motion/reactor/periodic_timer.rb
bubble-wrap-1.2.0.pre motion/reactor/periodic_timer.rb