Class: SingletonProcess
- Inherits:
-
Object
show all
- Defined in:
- lib/singleton_process.rb
Defined Under Namespace
Classes: AlreadyRunningError
Constant Summary
collapse
- VERSION =
File.read(File.expand_path('singleton_process/VERSION', File.dirname(__FILE__)))
Instance Attribute Summary collapse
Instance Method Summary
collapse
Constructor Details
#initialize(name, options = {}) ⇒ SingletonProcess
Returns a new instance of SingletonProcess.
13
14
15
16
17
|
# File 'lib/singleton_process.rb', line 13
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_name ⇒ Object
Returns the value of attribute app_name.
10
11
12
|
# File 'lib/singleton_process.rb', line 10
def app_name
@app_name
end
|
#name ⇒ Object
Returns the value of attribute name.
10
11
12
|
# File 'lib/singleton_process.rb', line 10
def name
@name
end
|
#root_path ⇒ Object
Returns the value of attribute root_path.
10
11
12
|
# File 'lib/singleton_process.rb', line 10
def root_path
@root_path
end
|
Instance Method Details
#lock ⇒ Object
32
33
34
35
36
|
# File 'lib/singleton_process.rb', line 32
def lock
write_pidfile
at_exit { delete_pidfile }
$0 = "#{app_name} | #{name} | started #{Time.now}"
end
|
#lock_or_exit ⇒ Object
38
39
40
41
42
|
# File 'lib/singleton_process.rb', line 38
def lock_or_exit
lock
rescue AlreadyRunningError
exit
end
|
#pid ⇒ Object
69
70
71
|
# File 'lib/singleton_process.rb', line 69
def pid
running? ? pidfile_path.read.to_i : nil
end
|
#pidfile_path ⇒ Object
28
29
30
|
# File 'lib/singleton_process.rb', line 28
def pidfile_path
pidfile_directory.join("#{name}.pid")
end
|
#run! ⇒ Object
44
45
46
47
48
|
# File 'lib/singleton_process.rb', line 44
def run!
lock
yield if block_given?
unlock
end
|
#running? ⇒ Boolean
55
56
57
58
59
60
61
62
63
64
65
66
67
|
# File 'lib/singleton_process.rb', line 55
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
|
#unlock ⇒ Object
50
51
52
53
|
# File 'lib/singleton_process.rb', line 50
def unlock
delete_pidfile
!running?
end
|