class Delayed::Backend::Mongoid::Job

Public Class Methods

after_fork() click to toggle source

Hook method that is called after a new worker is forked

# File lib/delayed/backend/mongoid.rb, line 86
def self.after_fork
  if ::Mongoid::Compatibility::Version.mongoid4?
    # to avoid `failed with error "unauthorized"` errors in Mongoid 4.0.alpha2
    ::Mongoid.default_session.disconnect
  end
end
clear_locks!(worker_name) click to toggle source

When a worker is exiting, make sure we don't have any locked jobs.

# File lib/delayed/backend/mongoid.rb, line 76
def self.clear_locks!(worker_name)
  where(locked_by: worker_name).update_all(locked_at: nil, locked_by: nil)
end
db_time_now() click to toggle source
# File lib/delayed/backend/mongoid.rb, line 27
def self.db_time_now
  Time.now.utc
end
reservation_criteria(worker, right_now, max_run_time) click to toggle source

Mongo criteria matching all the jobs the worker can reserver

Jobs are sorted by priority and run_at.

@api private

# File lib/delayed/backend/mongoid.rb, line 57
def self.reservation_criteria(worker, right_now, max_run_time)
  criteria = where(
    run_at: { '$lte' => right_now },
    failed_at: nil
  ).any_of(
    { locked_by: worker.name },
    { locked_at: nil },
    locked_at: { '$lt' => (right_now - max_run_time) }
  )

  criteria = criteria.gte(priority: Worker.min_priority.to_i) if Worker.min_priority
  criteria = criteria.lte(priority: Worker.max_priority.to_i) if Worker.max_priority
  criteria = criteria.any_in(queue: Worker.queues) if Worker.queues.any?
  criteria = criteria.desc(:locked_by).asc(:priority).asc(:run_at)

  criteria
end
reserve(worker, max_run_time = Worker.max_run_time) click to toggle source

Reserves one job for the worker.

Atomically picks and locks one job from the collection.

# File lib/delayed/backend/mongoid.rb, line 34
def self.reserve(worker, max_run_time = Worker.max_run_time)
  right_now = db_time_now

  criteria = reservation_criteria worker, right_now, max_run_time

  if ::Mongoid::Compatibility::Version.mongoid2? || ::Mongoid::Compatibility::Version.mongoid3? || ::Mongoid::Compatibility::Version.mongoid4?
    criteria.find_and_modify(
      { '$set' => { locked_at: right_now, locked_by: worker.name } },
      new: true
    )
  else
    criteria.find_one_and_update(
      { '$set' => { locked_at: right_now, locked_by: worker.name } },
      return_document: :after
    )
  end
end

Public Instance Methods

reload(*args) click to toggle source
Calls superclass method
# File lib/delayed/backend/mongoid.rb, line 80
def reload(*args)
  reset
  super
end