Class: Delayed::Backend::ActiveRecord::Job

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
Base
Defined in:
lib/delayed/backend/active_record.rb

Overview

A job object that is persisted to the database. Contains the work object as a YAML field.

Direct Known Subclasses

Failed

Defined Under Namespace

Classes: Failed

Constant Summary

Constants included from Base

Base::ON_HOLD_COUNT, Base::ON_HOLD_LOCKED_BY

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Base

#batch?, #failed?, #full_name, #hold!, included, #initialize_defaults, #invoke_job, #locked?, #name, #on_hold?, #payload_object, #payload_object=, #permanent_failure, #reschedule, #reschedule_at, #unhold!, #unlock

Class Method Details

.all_available(queue = Delayed::Settings.queue, min_priority = nil, max_priority = nil) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/delayed/backend/active_record.rb', line 206

def self.all_available(queue = Delayed::Settings.queue,
                       min_priority = nil,
                       max_priority = nil)
  min_priority ||= Delayed::MIN_PRIORITY
  max_priority ||= Delayed::MAX_PRIORITY

  check_queue(queue)
  check_priorities(min_priority, max_priority)

  self.ready_to_run.
      where(:priority => min_priority..max_priority, :queue => queue).
      by_priority
end

.bulk_update(action, opts) ⇒ Object

perform a bulk update of a set of jobs action is :hold, :unhold, or :destroy to specify the jobs to act on, either pass opts = [list of job ids] or opts = <some flavor> to perform on all jobs of that flavor



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/delayed/backend/active_record.rb', line 139

def self.bulk_update(action, opts)
  scope = if opts[:flavor]
    raise("Can't bulk update failed jobs") if opts[:flavor].to_s == 'failed'
    self.scope_for_flavor(opts[:flavor], opts[:query])
  elsif opts[:ids]
    self.where(:id => opts[:ids])
  end

  return 0 unless scope

  case action.to_s
  when 'hold'
    scope.update_all(:locked_by => ON_HOLD_LOCKED_BY, :locked_at => db_time_now, :attempts => ON_HOLD_COUNT)
  when 'unhold'
    now = db_time_now
    scope.update_all(["locked_by = NULL, locked_at = NULL, attempts = 0, run_at = (CASE WHEN run_at > ? THEN run_at ELSE ? END), failed_at = NULL", now, now])
  when 'destroy'
    scope.delete_all
  end
end

.by_priorityObject



70
71
72
# File 'lib/delayed/backend/active_record.rb', line 70

def self.by_priority
  order("priority ASC, run_at ASC")
end

.clear_locks!(worker_name) ⇒ Object

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



75
76
77
# File 'lib/delayed/backend/active_record.rb', line 75

def self.clear_locks!(worker_name)
  where(:locked_by => worker_name).update_all(:locked_by => nil, :locked_at => nil)
end

.create_singleton(options) ⇒ Object

Create the job on the specified strand, but only if there aren’t any other non-running jobs on that strand. (in other words, the job will still be created if there’s another job on the strand but it’s already running)



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/delayed/backend/active_record.rb', line 233

def self.create_singleton(options)
  strand = options[:strand]
  transaction_for_singleton(strand) do
    job = self.where(:strand => strand, :locked_at => nil).order(:id).first
    new_job = new(options)
    if job
      new_job.initialize_defaults
      job.run_at = [job.run_at, new_job.run_at].min
      job.save! if job.changed?
    else
      new_job.save!
    end
    job || new_job
  end
end

.currentObject



46
47
48
# File 'lib/delayed/backend/active_record.rb', line 46

def self.current
  where("run_at<=?", db_time_now)
end

.failedObject



54
55
56
# File 'lib/delayed/backend/active_record.rb', line 54

def self.failed
  where("failed_at IS NOT NULL")
end

.find_available(limit, queue = Delayed::Settings.queue, min_priority = nil, max_priority = nil) ⇒ Object



199
200
201
202
203
204
# File 'lib/delayed/backend/active_record.rb', line 199

def self.find_available(limit,
                        queue = Delayed::Settings.queue,
                        min_priority = nil,
                        max_priority = nil)
  all_available(queue, min_priority, max_priority).limit(limit).to_a
end

.futureObject



50
51
52
# File 'lib/delayed/backend/active_record.rb', line 50

def self.future
  where("run_at>?", db_time_now)
end

.get_and_lock_next_available(worker_name, queue = Delayed::Settings.queue, min_priority = nil, max_priority = nil) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/delayed/backend/active_record.rb', line 178

def self.get_and_lock_next_available(worker_name,
                                     queue = Delayed::Settings.queue,
                                     min_priority = nil,
                                     max_priority = nil)

  check_queue(queue)
  check_priorities(min_priority, max_priority)

  loop do
    jobs = find_available(Settings.fetch_batch_size, queue, min_priority, max_priority)
    return nil if jobs.empty?
    if Settings.select_random_from_batch
      jobs = jobs.sort_by { rand }
    end
    job = jobs.detect do |job|
      job.send(:lock_exclusively!, worker_name)
    end
    return job if job
  end
end

.jobs_count(flavor, query = nil) ⇒ Object

get the total job count for the given flavor see list_jobs for documentation on arguments



129
130
131
132
133
# File 'lib/delayed/backend/active_record.rb', line 129

def self.jobs_count(flavor,
                    query = nil)
  scope = self.scope_for_flavor(flavor, query)
  scope.count
end

.list_jobs(flavor, limit, offset = 0, query = nil) ⇒ Object

get a list of jobs of the given flavor in the given queue flavor is :current, :future, :failed, :strand or :tag depending on the flavor, query has a different meaning: for :current and :future, it’s the queue name (defaults to Delayed::Settings.queue) for :strand it’s the strand name for :tag it’s the tag name for :failed it’s ignored



118
119
120
121
122
123
124
125
# File 'lib/delayed/backend/active_record.rb', line 118

def self.list_jobs(flavor,
                   limit,
                   offset = 0,
                   query = nil)
  scope = self.scope_for_flavor(flavor, query)
  order = flavor.to_s == 'future' ? 'run_at' : 'id desc'
  scope.order(order).limit(limit).offset(offset).to_a
end

.ready_to_runObject

a nice stress test: 10_000.times { |i| Kernel.send_later_enqueue_args(:system, { :strand => ‘s1’, :run_at => (24.hours.ago + (rand(24.hours.to_i))) }, “echo #i >> test1.txt”) } 500.times { |i| “ohai”.send_later_enqueue_args(:reverse, { :run_at => (12.hours.ago + (rand(24.hours.to_i))) }) } then fire up your workers you can check out strand correctness: diff test1.txt <(sort -n test1.txt)



67
68
69
# File 'lib/delayed/backend/active_record.rb', line 67

def self.ready_to_run
  where("run_at<=? AND locked_at IS NULL AND next_in_strand=?", db_time_now, true)
end

.reconnect!Object



20
21
22
# File 'lib/delayed/backend/active_record.rb', line 20

def self.reconnect!
  clear_all_connections!
end

.runningObject



58
59
60
# File 'lib/delayed/backend/active_record.rb', line 58

def self.running
  where("locked_at IS NOT NULL AND locked_by<>'on hold'")
end

.running_jobsObject



83
84
85
# File 'lib/delayed/backend/active_record.rb', line 83

def self.running_jobs()
  self.running.order(:locked_at)
end

.scope_for_flavor(flavor, query) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/delayed/backend/active_record.rb', line 87

def self.scope_for_flavor(flavor, query)
  scope = case flavor.to_s
  when 'current'
    self.current
  when 'future'
    self.future
  when 'failed'
    Delayed::Job::Failed
  when 'strand'
    self.where(:strand => query)
  when 'tag'
    self.where(:tag => query)
  else
    raise ArgumentError, "invalid flavor: #{flavor.inspect}"
  end

  if %w(current future).include?(flavor.to_s)
    queue = query.presence || Delayed::Settings.queue
    scope = scope.where(:queue => queue)
  end

  scope
end

.strand_size(strand) ⇒ Object



79
80
81
# File 'lib/delayed/backend/active_record.rb', line 79

def self.strand_size(strand)
  self.where(:strand => strand).count
end

.tag_counts(flavor, limit, offset = 0) ⇒ Object

returns a list of hashes { :tag => tag_name, :count => current_count } in descending count order flavor is :current or :all

Raises:

  • (ArgumentError)


163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/delayed/backend/active_record.rb', line 163

def self.tag_counts(flavor,
                    limit,
                    offset = 0)
  raise(ArgumentError, "invalid flavor: #{flavor}") unless %w(current all).include?(flavor.to_s)
  scope = case flavor.to_s
    when 'current'
      self.current
    when 'all'
      self
    end

  scope = scope.group(:tag).offset(offset).limit(limit)
  scope.order("COUNT(tag) DESC").count.map { |t,c| { :tag => t, :count => c } }
end

.transaction_for_singleton(strand) ⇒ Object

used internally by create_singleton to take the appropriate lock depending on the db driver



222
223
224
225
226
227
# File 'lib/delayed/backend/active_record.rb', line 222

def self.transaction_for_singleton(strand)
  self.transaction do
    connection.execute(sanitize_sql(["SELECT pg_advisory_xact_lock(half_md5_as_bigint(?))", strand]))
    yield
  end
end

Instance Method Details

#create_and_lock!(worker) ⇒ Object



281
282
283
284
285
286
# File 'lib/delayed/backend/active_record.rb', line 281

def create_and_lock!(worker)
  raise "job already exists" unless new_record?
  self.locked_at = Delayed::Job.db_time_now
  self.locked_by = worker
  save!
end

#fail!Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/delayed/backend/active_record.rb', line 288

def fail!
  attrs = self.attributes
  attrs['original_job_id'] = attrs.delete('id')
  attrs['failed_at'] ||= self.class.db_time_now
  attrs.delete('next_in_strand')
  self.class.transaction do
    failed_job = Failed.create(attrs)
    self.destroy
    failed_job
  end
rescue
  # we got an error while failing the job -- we need to at least get
  # the job out of the queue
  self.destroy
  # re-raise so the worker logs the error, at least
  raise
end

#lock_strand_on_createObject



40
41
42
43
44
# File 'lib/delayed/backend/active_record.rb', line 40

def lock_strand_on_create
  if strand.present?
    self.class.connection.execute("SELECT pg_advisory_xact_lock(half_md5_as_bigint(#{self.class.sanitize(strand)}))")
  end
end