class RunChecker
This is class to check duplicated run
Public Class Methods
new(lock_path, logger = nil)
click to toggle source
- lock_path
-
lock file path
- logger
-
logger instance, it is expected a instance of Logger in Log4r. If you don’t set logger or you set nil for this param, log information will be put to stdout via StdoutOutputter.
# File lib/run_checker/run_checker.rb 12 def initialize(lock_path, logger = nil) 13 @lock_path = lock_path 14 @logger = logger 15 16 return if @logger 17 18 formatter = Log4r::PatternFormatter.new(pattern: '%d [%l]:%p: %M', 19 date_format: '%Y.%m.%d %H:%M:%S') 20 outputter = Log4r::StdoutOutputter.new('RunCheckerOutPutter', 21 formatter: formatter) 22 @logger = Log4r::Logger.new('RunChecker') 23 @logger.add(outputter) 24 end
Public Instance Methods
cleanup()
click to toggle source
# File lib/run_checker/run_checker.rb 64 def cleanup 65 return if !@lock_path || @lock_path.empty? 66 return unless File.exist? @lock_path 67 68 pid = 0 69 File.open(@lock_path, 'r') do |f| 70 pid = f.read.chomp!.to_i 71 end 72 73 if pid == $PROCESS_ID 74 File.delete(@lock_path) 75 else 76 @logger.info('lock file was created by other process') 77 end 78 end
lock()
click to toggle source
lock
- return
-
If this method returns true, other process didn’t run. If this method returns false, other process runs.
# File lib/run_checker/run_checker.rb 30 def lock 31 if !@lock_path || @lock_path.empty? 32 @logger.warn('lock file pass is nil') 33 return true 34 end 35 36 if File.exist? @lock_path 37 pid = 0 38 File.open(@lock_path, 'r') do |f| 39 pid = f.read.chomp!.to_i 40 end 41 42 if 0 != pid && exist_process(pid) 43 @logger.info("other process is running: pid(#{pid})") 44 return false 45 else 46 @logger.warn("process was finished pid(#{pid}), " + 47 'cleanup lock file and start new process') 48 File.delete(@lock_path) 49 end 50 end 51 52 File.open(@lock_path, 'w') do |f| 53 locked = f.flock(File::LOCK_EX | File::LOCK_NB) 54 if locked 55 f.puts $PROCESS_ID 56 return true 57 else 58 @logger.error("lock failed -> pid: #{$PID}") 59 return false 60 end 61 end 62 end
Private Instance Methods
exist_process(pid)
click to toggle source
# File lib/run_checker/run_checker.rb 82 def exist_process(pid) 83 Process.getpgid(pid) 84 return true 85 rescue => ex 86 @logger.info("check process error pid(#{pid}): #{ex}\n" + 87 ex.backtrace.join("\n ")) 88 return false 89 end