Skip to content

Instantly share code, notes, and snippets.

@zbelzer
Created April 14, 2010 14:42
Show Gist options
  • Save zbelzer/365881 to your computer and use it in GitHub Desktop.
Save zbelzer/365881 to your computer and use it in GitHub Desktop.
# Ruby code snippet:
def self.find_available(worker_name, limit = 6, max_run_time = Worker.max_run_time)
right_now = db_time_now
conditions = {
:run_at => {"$lte" => right_now},
:limit => -limit, # In mongo, positive limits are 'soft' and negative are 'hard'
:failed_at => nil,
:sort => [['priority', 1], ['run_at', 1]]
}
where = "this.locked_at == null || this.locked_at < #{make_date(right_now - max_run_time)}"
(conditions[:priority] ||= {})['$gte'] = Worker.min_priority.to_i if Worker.min_priority
(conditions[:priority] ||= {})['$lte'] = Worker.max_priority.to_i if Worker.max_priority
results = all(conditions.merge(:locked_by => worker_name))
results += all(conditions.merge('$where' => where)) if results.size < limit
results
end
# MongoDB client logs:
MONGODB likeassets-production.delayed_jobs.find({:$where=>"this.locked_at == null || this.locked_at < new Date(1271241350048.12)", :run_at=>{"$lte"=>Wed Apr 14 14:35:50 UTC 2010}, :priority=>{"$gte"=>0, "$lte"=> 90}, :failed_at=>nil}, {}).limit(-5)
# MongoDB server logs:
Wed Apr 14 06:37:11 query likeassets-production.delayed_jobs ntoreturn:5 reslen:36 nscanned:0 { query: { $where: "this.locked_at == null || this.locked_at < new Date(1271237830843.19)", run_at: { $lte: new Date(1271252230843) }, failed_at: null, priority: { $gte: 0, $lte: 90 } }, orderby: { priority: 1, run_at: 1 } } nreturned:0 589ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment