From fb7761bc053c182535005af104814dec4570c235 Mon Sep 17 00:00:00 2001 From: Hakan Ensari Date: Wed, 3 Oct 2018 14:22:52 +0100 Subject: [PATCH] Refactor daemon --- config/unicorn.rb | 4 +-- lib/scheduler.rb | 59 --------------------------------------- lib/scheduler/daemon.rb | 61 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 61 deletions(-) delete mode 100644 lib/scheduler.rb create mode 100644 lib/scheduler/daemon.rb diff --git a/config/unicorn.rb b/config/unicorn.rb index f0f69af..e1e49e0 100644 --- a/config/unicorn.rb +++ b/config/unicorn.rb @@ -10,8 +10,8 @@ initialized = false before_fork do |_server, _worker| Sequel::DATABASES.each(&:disconnect) unless initialized - require 'scheduler' - Scheduler.start + require 'scheduler/daemon' + Scheduler::Daemon.start initialized = true end end diff --git a/lib/scheduler.rb b/lib/scheduler.rb deleted file mode 100644 index a63a8f5..0000000 --- a/lib/scheduler.rb +++ /dev/null @@ -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 diff --git a/lib/scheduler/daemon.rb b/lib/scheduler/daemon.rb new file mode 100644 index 0000000..fc1d8d4 --- /dev/null +++ b/lib/scheduler/daemon.rb @@ -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