Module: SingleInstance

Defined in:
lib/single_instance.rb,
lib/single_instance/version.rb

Defined Under Namespace

Classes: Blocker

Constant Summary collapse

VERSION =
"0.3.1"

Class Method Summary collapse

Class Method Details

.exclusive_non_blocking(name, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/single_instance.rb', line 8

def exclusive_non_blocking(name, &block)
  lock_file = File.join(Dir::tmpdir, "single_instance_#{name}.pid")
  begin
    file = File.open(lock_file, "a+")
    file.rewind
    if file.flock(File::LOCK_EX|File::LOCK_NB)
      file.truncate(0)
      file.puts $$
      file.puts Time.now.to_i
      file.flush
      if block_given?
        yield nil
      else
        (@lock_files ||= []) << file
      end
    elsif block_given? && block.arity == 1
      pid = file.readline.to_i
      started_at = Time.at(file.readline.to_i)
      yield Blocker.new(pid, started_at)
    else
      false
    end
  ensure
    file.close if block_given?
  end
end