class TimeoutJob::Middleware

Public Instance Methods

call(worker, msg, queue) { || ... } click to toggle source
# File lib/timeout_job.rb, line 8
def call(worker, msg, queue, &block)
  if worker.respond_to?(:timeout_in)
    result = yield_with_timeout(worker.timeout_in, &block)

    if timeout?
      logger.info "TimeoutJob: The job of #{worker.class} timed out timeout_in=#{worker.timeout_in} args=#{truncate(msg['args'].inspect)}"
      logger.info 'TimeoutJob: ' + @error.backtrace.join("\n") if @error
      perform_callback(worker, :after_timeout, msg['args'])
      nil
    else
      result
    end
  else
    yield
  end
end
logger() click to toggle source
# File lib/timeout_job.rb, line 65
def logger
  if defined?(::Sidekiq)
    ::Sidekiq.logger
  elsif defined?(::Rails)
    ::Rails.logger
  else
    ::Logger.new(STDOUT)
  end
end
perform_callback(worker, callback_name, args) click to toggle source
# File lib/timeout_job.rb, line 40
def perform_callback(worker, callback_name, args)
  if worker.respond_to?(callback_name)
    parameters = worker.method(callback_name).parameters

    begin
      if parameters.empty?
        worker.send(callback_name)
      else
        worker.send(callback_name, *args)
      end
    rescue ArgumentError => e
      message = "The number of parameters of the callback method (#{parameters.size}) is not the same as the number of arguments (#{args.size})"
      raise ArgumentError.new("#{self.class}:#{worker.class} #{message} callback_name=#{callback_name} args=#{args.inspect} parameters=#{parameters.inspect}")
    end
  end
end
timeout?() click to toggle source
# File lib/timeout_job.rb, line 36
def timeout?
  @timeout
end
truncate(text, length: 100) click to toggle source
# File lib/timeout_job.rb, line 57
def truncate(text, length: 100)
  if text.length > length
    text.slice(0, length)
  else
    text
  end
end
yield_with_timeout(timeout_in) { || ... } click to toggle source
# File lib/timeout_job.rb, line 25
def yield_with_timeout(timeout_in, &block)
  @timeout = false
  ::Timeout.timeout(timeout_in) do
    yield
  end
rescue ::Timeout::Error => e
  @timeout = true
  @error = e
  nil
end