diff --git a/lib/que/command_line_interface.rb b/lib/que/command_line_interface.rb index 9b869938..7e9f2e67 100644 --- a/lib/que/command_line_interface.rb +++ b/lib/que/command_line_interface.rb @@ -159,6 +159,14 @@ def parse( ) do |p| options[:wait_period] = p end + + opts.on( + '--pidfile [PATH]', + String, + "Write the PID of this process to the specified file.", + ) do |p| + options[:pidfile] = File.expand_path(p) + end end parser.parse!(args) diff --git a/lib/que/locker.rb b/lib/que/locker.rb index b823a742..cb7ec40a 100644 --- a/lib/que/locker.rb +++ b/lib/que/locker.rb @@ -61,7 +61,8 @@ def initialize( wait_period: DEFAULT_WAIT_PERIOD, maximum_buffer_size: DEFAULT_MAXIMUM_BUFFER_SIZE, worker_priorities: DEFAULT_WORKER_PRIORITIES, - on_worker_start: nil + on_worker_start: nil, + pidfile: nil ) # Sanity-check all our arguments, since some users may instantiate Locker @@ -215,10 +216,16 @@ def initialize( @connection.wrapped_connection.close end end + + @pidfile = pidfile + at_exit { delete_pid } + write_pid end def stop! - stop; wait_for_stop + stop + wait_for_stop + delete_pid end def stop @@ -512,5 +519,19 @@ def mark_id_as_locked(id) "Tried to lock a job that was already locked: #{id}" end end + + def write_pid + return unless @pidfile + + File.open(@pidfile, "w+") do |f| + f.write(Process.pid.to_s) + end + end + + def delete_pid + return unless @pidfile + + File.delete(@pidfile) if File.exist?(@pidfile) + end end end diff --git a/spec/que/locker_spec.rb b/spec/que/locker_spec.rb index af174c2c..80b8276f 100644 --- a/spec/que/locker_spec.rb +++ b/spec/que/locker_spec.rb @@ -185,6 +185,30 @@ def assert_que_locker_insertion( locker.stop! end + describe "with pidfile" do + it "should create and delete pid file, if not exist" do + pidfile = "./spec/temp/pidfile_#{Time.new.to_i}.pid" + locker_settings[:pidfile] = pidfile + locker + assert File.exist?(pidfile) + + locker.stop! + refute File.exist?(pidfile) + end + + it "should create and delete pid file, if exist" do + pidfile = "./spec/temp/pidfile_#{Time.new.to_i}.pid" + File.open(pidfile, "w+") { |f| f.write "test" } + + locker_settings[:pidfile] = pidfile + locker + assert File.exist?(pidfile) + + locker.stop! + refute File.exist?(pidfile) + end + end + describe "on startup" do it "should do batch polls for jobs in its specified queue" do job1, job2 = BlockJob.enqueue, BlockJob.enqueue