Sha256: 56c4041b436b8b453ac19d78c2da80ef5c7a47b11c347f89f47807ccf75f57b0

Contents?: true

Size: 1.05 KB

Versions: 6

Compression:

Stored size: 1.05 KB

Contents

module Workers
  class Timer
    include Workers::Helpers

    attr_reader :delay
    attr_reader :repeat

    def initialize(delay, options = {}, &block)
      @logger = Workers::LogProxy.new(options[:logger])
      @delay = delay
      @callback = options[:callback] || block
      @repeat = options[:repeat] || false
      @scheduler = options[:scheduler] || Workers.scheduler

      @mutex = Mutex.new

      reset

      @scheduler.schedule(self)
    end

    def <=>(other)
      return sec_remaining <=> other.sec_remaining
    end

    def sec_remaining
      @mutex.synchronize do
        diff = @fire_at.to_f - Time.now.utc.to_f

        return (diff > 0) ? diff : 0
      end
    end

    def overdue?
        return sec_remaining <= 0
    end

    def fire
      @mutex.synchronize do
        @callback.call if @callback
      end

      return nil
    end

    def cancel
      @scheduler.unschedule(self)

      return nil
    end

    def reset
      @mutex.synchronize do
        @fire_at = Time.now.utc + @delay
      end

      return nil
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
workers-0.0.9 lib/workers/timer.rb
workers-0.0.8 lib/workers/timer.rb
workers-0.0.7 lib/workers/timer.rb
workers-0.0.6 lib/workers/timer.rb
workers-0.0.5 lib/workers/timer.rb
workers-0.0.4 lib/workers/timer.rb