Sha256: 35a1520619bde2acf747c7453df3f27b53a483b6b687bb062a3812849faf46f2

Contents?: true

Size: 1.6 KB

Versions: 6

Compression:

Stored size: 1.6 KB

Contents

module Triglav::Agent
  # A timer utility to run serverengine worker in a time interval
  #
  #     module Triglav::Agent
  #       module Worker
  #         def initialize
  #           @interval = 60.0 # sec
  #         end
  #
  #         def run
  #           @timer = Timer.new
  #           @stop = false
  #           until @stop
  #             @timer.wait(@interval) { process }
  #           end
  #         end
  #
  #         def stop
  #           @stop = true
  #           @timer.stop
  #         end
  #       end
  #     end
  class Timer
    def initialize
      @r, @w = IO.pipe
      start
    end

    def wait(sec, &block)
      return if @stop
      started = Time.now
      yield
      elapsed = Time.now - started
      if (timeout = (sec - elapsed).to_f) > 0
        begin
          IO.select([@r], [], [], timeout)
        rescue IOError, Errno::EBADF
          # these error may occur if @r is closed during IO.select. Ignore it
        end
      end
    end

    def start
      @stop = false
    end

    def stop
      @stop = true
      signal
    end

    private

    def signal
      @w.puts ' '
    end

    # # Hmm, Ctrl-C breaks condvar.wait before calling #stop unexpectedly
    # attr_reader :condvar, :mutex
    #
    # def initialize
    #   @condvar = ConditionVariable.new
    #   @mutex = Mutex.new
    # end
    #
    # def wait(sec, &block)
    #   started = Time.now
    #   @mutex.synchronize do
    #     yield
    #     elapsed = (Time.now - started).to_f
    #     @condvar.wait(@mutex, sec - elapsed)
    #   end
    # end
    #
    # def signal
    #   @condvar.signal
    # end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
triglav-agent-1.0.0 lib/triglav/agent/timer.rb
triglav-agent-1.0.0.rc3 lib/triglav/agent/timer.rb
triglav-agent-1.0.0.rc2 lib/triglav/agent/timer.rb
triglav-agent-1.0.0.rc1 lib/triglav/agent/timer.rb
triglav-agent-1.0.0.pre2 lib/triglav/agent/timer.rb
triglav-agent-1.0.0.pre1 lib/triglav/agent/timer.rb