require 'delayed_job' module JobsAutoscaling class Monitor IDLE = :idle BUSY = :busy def initialize(action: action) @action = action end def activate! Delayed::Worker.lifecycle.after(:work_queue_pop, &method(:work_queue_pop)) change_state(IDLE) end protected def work_queue_pop(work_queue) unless work_queue.respond_to?(:all_workers_idle?) raise("JobsAutoscaling requires a ParentProcess work queue") end new_state = work_queue.all_workers_idle? ? IDLE : BUSY if new_state != @worker_state change_state(new_state) end end def change_state(new_state) @worker_state = new_state @action.public_send(new_state) end end end