Module: FlockSynchronize
- Defined in:
- lib/flock_synchronize.rb,
lib/flock_synchronize/version.rb
Constant Summary collapse
- VERSION =
"1.2.0"
Class Method Summary collapse
-
.flock_synchronize(key, options = {}) ⇒ Object
flock_synchronize wraps a block with a flock-based mutex.
Class Method Details
.flock_synchronize(key, options = {}) ⇒ Object
flock_synchronize wraps a block with a flock-based mutex.
Any other process calling flock_synchronize with the same key will wait for the previous block to exit before executing.
NOTE: This only works on a per-process basis and is not compatible with Ruby threads. For that, see the built-in Mutex library
FlockSynchronize.flock_synchronize("my operation") do
some.code_that_needs(synchronizing)
end
Options available:
locking_constant: use a different constant than LOCK_EX. See the
File.flock documentation for more info.
timeout: automatically unlock if the lock was created more
this number of seconds ago
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/flock_synchronize.rb', line 24 def self.flock_synchronize(key, ={}) # Previous versions took locking_constant as second param and now it's # a hash if !.kind_of? Hash = {locking_constant: } end [:locking_constant] ||= File::LOCK_EX filename = File.join(Dir.tmpdir, "#{key}.flock") begin if [:timeout] if File.exists? filename and (Time.now - File.mtime(filename)) > [:timeout] File.unlink filename end end File.open(filename, 'w') do |f| f.flock([:locking_constant]) yield end ensure File.unlink filename if File.exists? filename end end |