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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, downtime: 30, logger: Logger.new(STDOUT), redis: Redis.new) ⇒ UniqueThread

Returns a new instance of UniqueThread.



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

def initialize(name, downtime: 30, logger: Logger.new(STDOUT), redis: Redis.new)
  @logger    = logger
  @stopwatch = Stopwatch.new(downtime: downtime)
  @locksmith = Locksmith.new(name: name, stopwatch: stopwatch, redis: redis, logger: logger)
end

Instance Attribute Details

#locksmithObject (readonly)

Returns the value of attribute locksmith.



9
10
11
# File 'lib/unique_thread.rb', line 9

def locksmith
  @locksmith
end

#loggerObject (readonly)

Returns the value of attribute logger.



9
10
11
# File 'lib/unique_thread.rb', line 9

def logger
  @logger
end

#stopwatchObject (readonly)

Returns the value of attribute stopwatch.



9
10
11
# File 'lib/unique_thread.rb', line 9

def stopwatch
  @stopwatch
end

Instance Method Details

#run(&block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/unique_thread.rb', line 17

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

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