Refactor daemon

This commit is contained in:
Hakan Ensari 2018-10-03 14:22:52 +01:00
parent 339ccbd743
commit fb7761bc05
3 changed files with 63 additions and 61 deletions

View File

@ -10,8 +10,8 @@ initialized = false
before_fork do |_server, _worker| before_fork do |_server, _worker|
Sequel::DATABASES.each(&:disconnect) Sequel::DATABASES.each(&:disconnect)
unless initialized unless initialized
require 'scheduler' require 'scheduler/daemon'
Scheduler.start Scheduler::Daemon.start
initialized = true initialized = true
end end
end end

View File

@ -1,59 +0,0 @@
# frozen_string_literal: true
class Scheduler
attr_reader :pid
def self.start
new.start
end
def initialize
@parent_pid = Process.pid
end
def start
return if pid
@pid = fork do
monitor_parent
run
end
monitor_child
end
private
def run
load 'bin/schedule'
end
def monitor_child
return if @child_monitor
@child_monitor = Thread.new do
loop do
sleep 5
unless alive?(pid)
@pid = nil
start
end
end
end
end
def monitor_parent
Thread.new do
loop do
exit unless alive?(@parent_pid)
sleep 1
end
end
end
def alive?(pid)
Process.getpgid(pid)
true
rescue Errno::ESRCH
false
end
end

61
lib/scheduler/daemon.rb Normal file
View File

@ -0,0 +1,61 @@
# frozen_string_literal: true
module Scheduler
class Daemon
attr_reader :pid
def self.start
new.start
end
def initialize
@parent_pid = Process.pid
end
def start
return if pid
@pid = fork do
monitor_parent
run
end
monitor_child
end
private
def run
load 'bin/schedule'
end
def monitor_child
return if @child_monitor
@child_monitor = Thread.new do
loop do
sleep 5
unless alive?(pid)
@pid = nil
start
end
end
end
end
def monitor_parent
Thread.new do
loop do
exit unless alive?(@parent_pid)
sleep 1
end
end
end
def alive?(pid)
Process.getpgid(pid)
true
rescue Errno::ESRCH
false
end
end
end