Module: Sequel::Synchronize

Defined in:
lib/sequel/extensions/synchronize.rb

Overview

Allows you to use PostgreSQL transaction advisory locks for application-level mutexes

Constant Summary collapse

AdvisoryLockTimeoutError =
Class.new(StandardError)
LOCK_RETRY_INTERVAL =
0.5

Instance Method Summary collapse

Instance Method Details

#synchronize_with(*args, timeout: 10, savepoint: false, skip_if_locked: false) ⇒ Object

Use transaction advisory lock for block of code

> BEGIN

> SELECT pg_try_advisory_xact_lock(3764656399) – ‘ruby-forever’

> COMMIT

Examples:

DB.synchronize_with([:ruby, :forever]) { p "Hey, I'm in transaction!"; sleep 5 }


24
25
26
27
28
29
30
31
32
33
34
# File 'lib/sequel/extensions/synchronize.rb', line 24

def synchronize_with(*args, timeout: 10, savepoint: false, skip_if_locked: false)
  key = lock_key_for(args)

  transaction(savepoint: savepoint) do
    hash = key_hash(key)
    if get_lock(key, hash, timeout: timeout, skip_if_locked: skip_if_locked)
      log_info("locked with #{key} (#{hash})")
      yield
    end
  end
end