Sha256: d64b09ffad94171e203e3a872c8d5b44c1d46edea82b10b2c38f441194817cd7

Contents?: true

Size: 1.23 KB

Versions: 4

Compression:

Stored size: 1.23 KB

Contents

require 'delayed_job'

module JobsAutoscaling
  class Monitor
    IDLE = :idle
    BUSY = :busy

    def initialize(action: )
      @actions = Array(action)
    end

    def activate!
      Delayed::Worker.lifecycle.after(:check_for_work, &method(:check_for_work))
      load_preexisting_jobs
      change_state(preexisting_jobs_running? ? BUSY : IDLE)
    end

    protected

    def load_preexisting_jobs
      @process_mtime_map = {}
      Delayed::Job.processes_locked_locally.each do |pid|
        mtime = Delayed::Worker::ProcessHelper.mtime(pid)
        @process_mtime_map[pid] = mtime if mtime
      end
    end

    def preexisting_jobs_running?
      @process_mtime_map.each do |pid, mtime|
        unless Delayed::Worker::ProcessHelper.process_is_still_running?(pid, mtime)
          @process_mtime_map.delete(pid)
        end
      end
      @process_mtime_map.any?
    end

    def check_for_work(work_queue)
      new_state = work_queue.all_workers_idle? && !preexisting_jobs_running? ? IDLE : BUSY
      if new_state != @worker_state
        change_state(new_state)
      end
    end

    def change_state(new_state)
      @worker_state = new_state
      @actions.each do |action|
        action.public_send(new_state)
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
inst-jobs-autoscaling-2.1.1 lib/jobs_autoscaling/monitor.rb
inst-jobs-autoscaling-2.1.0 lib/jobs_autoscaling/monitor.rb
inst-jobs-autoscaling-2.0.0 lib/jobs_autoscaling/monitor.rb
inst-jobs-autoscaling-1.0.5 lib/jobs_autoscaling/monitor.rb