Class: UniqueThread

Inherits:
Object
  • Object
show all
Defined in:
lib/unique_thread.rb,
lib/unique_thread/locksmith.rb,
lib/unique_thread/stopwatch.rb

Defined Under Namespace

Classes: HeldLock, Lock, Locksmith, Stopwatch

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, downtime: 30) ⇒ UniqueThread

Returns a new instance of UniqueThread.



36
37
38
39
# File 'lib/unique_thread.rb', line 36

def initialize(name, downtime: 30)
  @stopwatch = Stopwatch.new(downtime: downtime)
  @locksmith = Locksmith.new(name: name, stopwatch: stopwatch)
end

Class Attribute Details

.loggerObject



12
13
14
# File 'lib/unique_thread.rb', line 12

def logger
  @logger ||= default_logger
end

.redisObject



16
17
18
# File 'lib/unique_thread.rb', line 16

def redis
  @redis ||= Redis.new
end

Instance Attribute Details

#locksmithObject (readonly)

Returns the value of attribute locksmith.



34
35
36
# File 'lib/unique_thread.rb', line 34

def locksmith
  @locksmith
end

#stopwatchObject (readonly)

Returns the value of attribute stopwatch.



34
35
36
# File 'lib/unique_thread.rb', line 34

def stopwatch
  @stopwatch
end

Instance Method Details

#run(&block) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/unique_thread.rb', line 41

def run(&block)
  safe_infinite_loop do
    lock = locksmith.new_lock

    if lock.acquired?
      self.class.logger.info('Lock acquired! Running the unique thread.')
      lock.while_held(&block)
    else
      self.class.logger.debug('Could not acquire the lock. Sleeping until next attempt.')
      stopwatch.sleep_until_next_attempt(lock.locked_until.to_f)
    end
  end
end