def lock
      acquire

      @refresh_thread = Thread.new do
        renew_interval = [1.0, @expiration/2].max

        begin
          done_refreshing = false
          until @unlock || done_refreshing
            @refresh_mutex.synchronize do
              @refresh_signal.wait(@refresh_mutex, renew_interval)
              break if @unlock

              @logger.debug("Renewing lock: #@name")
              lock_expiration = Time.now.to_f + @expiration + 1

              if Models::Lock.where(name: @name, uid: @uid).update(expired_at: Time.at(lock_expiration)) == 0
                done_refreshing = true
              end
            end
          end
        ensure
          if !@unlock
            Models::Event.create(
              user: Config.current_job.username,
              action: 'lost',
              object_type: 'lock',
              object_name: @name,
              task: @task_id,
              deployment: @deployment_name,
              error: 'Lock renewal thread exiting',
              timestamp: Time.now,
            )

            Models::Task[@task_id].update(state: 'cancelling')

            @logger.debug('Lock renewal thread exiting')
          end
        end
      end

      if block_given?
        begin
          yield
        ensure
          release
        end
      end
    end
def lock
      acquire

      @refresh_thread = Thread.new do
        renew_interval = [1.0, @expiration/2].max

        begin
          done_refreshing = false
          until @unlock || done_refreshing
            @refresh_mutex.synchronize do
              @refresh_signal.wait(@refresh_mutex, renew_interval)
              break if @unlock

              @logger.debug("Renewing lock: #@name")
              lock_expiration = Time.now.to_f + @expiration + 1

              if Models::Lock.where(name: @name, uid: @uid).update(expired_at: Time.at(lock_expiration)) == 0
                done_refreshing = true
              end
            end
          end
        ensure
          if !@unlock
            Models::Event.create(
              user: Config.current_job.username,
              action: 'lost',
              object_type: 'lock',
              object_name: @name,
              task: @task_id,
              deployment: @deployment_name,
              error: 'Lock renewal thread exiting',
              timestamp: Time.now,
            )

            Models::Task[@task_id].update(state: 'cancelling')

            @logger.debug('Lock renewal thread exiting')
          end
        end
      end

      if block_given?
        begin
          yield
        ensure
          release
        end
      end
    end
Creates new lock with the given name.

 @param name lock name
 @option opts [Number] timeout how long to wait before giving up
 @option opts [Number] expiration how long to wait before expiring an old
   lock
 Acquire a lock.

 @yield [void] optional block to do work before automatically releasing
   the lock.
 @return [void]