Class: Rufus::Scheduler::FileLock

Inherits:
Object
  • Object
show all
Defined in:
lib/rufus/scheduler/locks.rb

Overview

The standard flock mechanism, with its own class thanks to @ecin

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ FileLock

Returns a new instance of FileLock.



25
26
27
28
# File 'lib/rufus/scheduler/locks.rb', line 25

def initialize(path)

  @path = path.to_s
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



23
24
25
# File 'lib/rufus/scheduler/locks.rb', line 23

def path
  @path
end

Instance Method Details

#lockObject

Locking is successful if this Ruby process can create and lock its lockfile (at the given path).



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rufus/scheduler/locks.rb', line 33

def lock

  return true if locked?

  @lockfile = nil

  FileUtils.mkdir_p(::File.dirname(@path))

  file = File.new(@path, File::RDWR | File::CREAT)
  locked = file.flock(File::LOCK_NB | File::LOCK_EX)

  return false unless locked

  now = Time.now

  file.print("pid: #{$$}, ")
  file.print("scheduler.object_id: #{self.object_id}, ")
  file.print("time: #{now}, ")
  file.print("timestamp: #{now.to_f}")
  file.flush

  @lockfile = file

  true
end

#locked?Boolean

Returns:

  • (Boolean)


64
65
66
67
# File 'lib/rufus/scheduler/locks.rb', line 64

def locked?

  !! (@lockfile && @lockfile.flock(File::LOCK_NB | File::LOCK_EX))
end

#unlockObject



59
60
61
62
# File 'lib/rufus/scheduler/locks.rb', line 59

def unlock

  !! (@lockfile && @lockfile.flock(File::LOCK_UN))
end