Class: MiniScheduler::DistributedMutex
- Inherits:
-
Object
- Object
- MiniScheduler::DistributedMutex
- Defined in:
- lib/mini_scheduler/distributed_mutex.rb
Defined Under Namespace
Classes: Timeout
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(key, redis) ⇒ DistributedMutex
constructor
A new instance of DistributedMutex.
-
#synchronize ⇒ Object
NOTE wrapped in mutex to maintain its semantics.
Constructor Details
#initialize(key, redis) ⇒ DistributedMutex
Returns a new instance of DistributedMutex.
18 19 20 21 22 23 |
# File 'lib/mini_scheduler/distributed_mutex.rb', line 18 def initialize(key, redis) raise ArgumentError.new("redis argument is nil") if redis.nil? @key = key @redis = redis @mutex = Mutex.new end |
Class Method Details
.redis=(redis) ⇒ Object
10 11 12 |
# File 'lib/mini_scheduler/distributed_mutex.rb', line 10 def self.redis=(redis) @default_redis = redis end |
.synchronize(key, redis = nil, &blk) ⇒ Object
14 15 16 |
# File 'lib/mini_scheduler/distributed_mutex.rb', line 14 def self.synchronize(key, redis = nil, &blk) self.new(key, redis || @default_redis).synchronize(&blk) end |
Instance Method Details
#synchronize ⇒ Object
NOTE wrapped in mutex to maintain its semantics
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/mini_scheduler/distributed_mutex.rb', line 30 def synchronize @mutex.lock attempts = 0 sleep_duration = BASE_SLEEP_DURATION while !try_to_get_lock sleep(sleep_duration) if sleep_duration < MAX_SLEEP_DURATION sleep_duration = [sleep_duration * 2, MAX_SLEEP_DURATION].min end attempts += 1 raise Timeout if attempts >= MAX_POLLING_ATTEMPTS end yield ensure @redis.del @key @mutex.unlock end |