Class: SingletonProcess

Inherits:
Object
  • Object
show all
Defined in:
lib/singleton_process.rb

Defined Under Namespace

Classes: AlreadyRunningError

Constant Summary collapse

VERSION =
'0.0.3'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ SingletonProcess

Returns a new instance of SingletonProcess.



11
12
13
14
15
# File 'lib/singleton_process.rb', line 11

def initialize(name, options = {})
  self.name      = name
  self.root_path = options.fetch(:root_path, nil)
  self.app_name  = options.fetch(:app_name, nil)
end

Instance Attribute Details

#app_nameObject

Returns the value of attribute app_name.



8
9
10
# File 'lib/singleton_process.rb', line 8

def app_name
  @app_name
end

#nameObject

Returns the value of attribute name.



8
9
10
# File 'lib/singleton_process.rb', line 8

def name
  @name
end

#root_pathObject

Returns the value of attribute root_path.



8
9
10
# File 'lib/singleton_process.rb', line 8

def root_path
  @root_path
end

Instance Method Details

#lockObject



30
31
32
33
34
# File 'lib/singleton_process.rb', line 30

def lock
  write_pidfile
  at_exit { delete_pidfile }
  $0 = "#{app_name} | #{name} | started #{Time.now}"
end

#lock_or_exitObject



36
37
38
39
40
# File 'lib/singleton_process.rb', line 36

def lock_or_exit
  lock
rescue AlreadyRunningError
  exit
end

#pidObject



67
68
69
# File 'lib/singleton_process.rb', line 67

def pid
  running? ? pidfile_path.read.to_i : nil
end

#pidfile_pathObject



26
27
28
# File 'lib/singleton_process.rb', line 26

def pidfile_path
  pidfile_directory.join("#{name}.pid")
end

#run!Object



42
43
44
45
46
# File 'lib/singleton_process.rb', line 42

def run!
  lock
  yield if block_given?
  unlock
end

#running?Boolean

Returns:

  • (Boolean)


53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/singleton_process.rb', line 53

def running?
  if pidfile_path.exist?
    local_pidfile = pidfile_path.open('a')
    !local_pidfile.flock(File::LOCK_EX | File::LOCK_NB)
  else
    false
  end
ensure
  if local_pidfile
    local_pidfile.flock(File::LOCK_UN)
    local_pidfile.close
  end
end

#unlockObject



48
49
50
51
# File 'lib/singleton_process.rb', line 48

def unlock
  delete_pidfile
  !running?
end