Sha256: 166d64f0478412fd877fe7c26e80d4adbc7417ab8b3ee7294af4ea6612346053

Contents?: true

Size: 1.92 KB

Versions: 3

Compression:

Stored size: 1.92 KB

Contents

require "eventmachine"
require "observed/eventmachine/version"

module Observed
  module EM

    # Schedule the observation to run it periodically
    # @param [Float|Fixnum] seconds
    # @param [Hash] args
    # @option args [String] :run The tag of the observation to schedule running. It is the one registered via the code
    #                            `observe tag, via: 'observer_plugin_name'`.
    def every(seconds, args)
      @builder.every seconds, args
    end

    # Start EventMachine and run scheduled observations.
    def start
      ::EM.run do
        Signal.trap("INT")  { ::EventMachine.stop }
        Signal.trap("TERM") { ::EventMachine.stop }
        @builder.periodic_tasks.each do |periodic_task|
          ::EM.add_periodic_timer(periodic_task.seconds) do
            ::EM.defer { run(periodic_task.tag) }
          end
        end
      end
    end

    # Automatically called on `extend Observed::EM`
    def init_observed_em_builder
      @builder = Builder.new
    end

    def self.extended(klass)
      klass.init_observed_em_builder
    end

    class Builder

      # Schedule the observation to run it periodically.
      # Scheduled observations can be obtained later by calling the method `periodic_tasks`.
      # @param [Float|Fixnum] seconds The interval to run the observation, in seconds.
      # @param [Hash] args
      # @option args [String] :run The tag of the observation to schedule running. It is the one registered via the code
      #                            `observe tag, via: 'observer_plugin_name'`.
      def every(seconds, args)
        periodic_tasks << PeriodicTask.new(seconds, args)
      end

      def periodic_tasks
        @periodic_tasks ||= []
      end
    end

    class PeriodicTask
      attr_reader :seconds
      attr_reader :args

      def initialize(seconds, args)
        @seconds = seconds
        @args = args
      end

      def tag
        args[:run]
      end
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
observed-0.2.0 integrations/observed-eventmachine/lib/observed/eventmachine.rb
observed-0.2.0.rc2 integrations/observed-eventmachine/lib/observed/eventmachine.rb
observed-0.2.0.rc1 integrations/observed-eventmachine/lib/observed/eventmachine.rb