Sha256: 3b8ec104113b51f3fbb9be6b39419f59dd62565429e493c388df0696235d3e85

Contents?: true

Size: 1.55 KB

Versions: 21

Compression:

Stored size: 1.55 KB

Contents

module Bluepill
  class Trigger
    @implementations = {}
    def self.inherited(klass)
      @implementations[klass.name.split('::').last.underscore.to_sym] = klass
    end
    
    def self.[](name)
      @implementations[name]
    end

    attr_accessor :process, :logger, :mutex, :scheduled_events
    
    def initialize(process, options = {})
      self.process = process
      self.logger = options[:logger]
      self.mutex = Mutex.new
      self.scheduled_events = []
    end
    
    def reset!
      self.cancel_all_events
    end
    
    def notify(transition)
      raise "Implement in subclass"
    end
    
    def dispatch!(event)
      self.process.dispatch!(event, self.class.name.split("::").last)
    end
    
    def schedule_event(event, delay)
      # TODO: maybe wrap this in a ScheduledEvent class with methods like cancel
      thread = Thread.new(self) do |trigger|
        begin
          sleep delay.to_f
          trigger.logger.info("Retrying from flapping")
          trigger.dispatch!(event)
          trigger.mutex.synchronize do
            trigger.scheduled_events.delete_if { |_, thread| thread == Thread.current }
          end
        rescue StandardError => e
          trigger.logger.err(e)
          trigger.logger.err(e.backtrace.join("\n"))
        end
      end
      
      self.scheduled_events.push([event, thread])
    end
    
    def cancel_all_events
      self.logger.info "Canceling all scheduled events"
      self.mutex.synchronize do
        self.scheduled_events.each {|_, thread| thread.kill}
      end
    end
    
  end
end

Version data entries

21 entries across 21 versions & 6 rubygems

Version Path
mwotton-bluepill-0.0.44 lib/bluepill/trigger.rb
ra-bluepill-0.0.44 lib/bluepill/trigger.rb
bluepill-0.0.44 lib/bluepill/trigger.rb
sumskyi-bluepill-0.0.42.1 lib/bluepill/trigger.rb
sumskyi-bluepill-0.0.42.0 lib/bluepill/trigger.rb
bluepill-0.0.43 lib/bluepill/trigger.rb
bluepill-0.0.42 lib/bluepill/trigger.rb
bluepill-0.0.40 lib/bluepill/trigger.rb
dylanvaughn-bluepill-0.0.40 lib/bluepill/trigger.rb
dylanvaughn-bluepill-0.0.39 lib/bluepill/trigger.rb
bluepill-0.0.39 lib/bluepill/trigger.rb
bluepill-0.0.38 lib/bluepill/trigger.rb
bluepill-0.0.37 lib/bluepill/trigger.rb
bluepill-0.0.36 lib/bluepill/trigger.rb
bluepill-0.0.35 lib/bluepill/trigger.rb
bluepill-0.0.34 lib/bluepill/trigger.rb
bluepill-0.0.33 lib/bluepill/trigger.rb
wijet-bluepill-0.0.33 lib/bluepill/trigger.rb
bluepill-0.0.32 lib/bluepill/trigger.rb
bluepill-0.0.31 lib/bluepill/trigger.rb