Class | Delayed::Backend::ActiveRecord::Job |
In: |
lib/delayed/backend/active_record.rb
|
Parent: | ::ActiveRecord::Base |
A job object that is persisted to the database. Contains the work object as a YAML field.
# File lib/delayed/backend/active_record.rb, line 23 23: def self.after_fork 24: ::ActiveRecord::Base.establish_connection 25: end
# File lib/delayed/backend/active_record.rb, line 19 19: def self.before_fork 20: ::ActiveRecord::Base.clear_all_connections! 21: end
When a worker is exiting, make sure we don‘t have any locked jobs.
# File lib/delayed/backend/active_record.rb, line 28 28: def self.clear_locks!(worker_name) 29: update_all("locked_by = null, locked_at = null", ["locked_by = ?", worker_name]) 30: end
Get the current time (GMT or local depending on DB) Note: This does not ping the DB to get the time, so all your clients must have syncronized clocks.
# File lib/delayed/backend/active_record.rb, line 69 69: def self.db_time_now 70: if Time.zone 71: Time.zone.now 72: elsif ::ActiveRecord::Base.default_timezone == :utc 73: Time.now.utc 74: else 75: Time.now 76: end 77: end
Find a few candidate jobs to run (in case some immediately get locked by others).
# File lib/delayed/backend/active_record.rb, line 33 33: def self.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time) 34: scope = self.ready_to_run(worker_name, max_run_time) 35: scope = scope.scoped(:conditions => ['priority >= ?', Worker.min_priority]) if Worker.min_priority 36: scope = scope.scoped(:conditions => ['priority <= ?', Worker.max_priority]) if Worker.max_priority 37: 38: ::ActiveRecord::Base.silence do 39: scope.by_priority.all(:limit => limit) 40: end 41: end
Lock this job for this worker. Returns true if we have the lock, false otherwise.
# File lib/delayed/backend/active_record.rb, line 45 45: def lock_exclusively!(max_run_time, worker) 46: now = self.class.db_time_now 47: affected_rows = if locked_by != worker 48: # We don't own this job so we will update the locked_by name and the locked_at 49: self.class.update_all(["locked_at = ?, locked_by = ?", now, worker], ["id = ? and (locked_at is null or locked_at < ?) and (run_at <= ?)", id, (now - max_run_time.to_i), now]) 50: else 51: # We already own this job, this may happen if the job queue crashes. 52: # Simply resume and update the locked_at 53: self.class.update_all(["locked_at = ?", now], ["id = ? and locked_by = ?", id, worker]) 54: end 55: if affected_rows == 1 56: self.locked_at = now 57: self.locked_by = worker 58: self.locked_at_will_change! 59: self.locked_by_will_change! 60: return true 61: else 62: return false 63: end 64: end