Class: Delayed::Job

Inherits:
ActiveRecord::Base show all
Includes:
Backend::Base
Defined in:
app/models/delayed/job.rb

Constant Summary collapse

REENQUEUE_BUFFER =
30.seconds

Constants included from Backend::Base

Backend::Base::ParseObjectFromYaml

Instance Attribute Summary

Attributes included from Backend::Base

#error

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Backend::Base

#destroy_failed_jobs?, #fail!, #failed?, #hook, included, #invoke_job, #max_attempts, #max_run_time, #name, #payload_object, #payload_object=, #priority, #priority=, #reschedule_at, #unlock

Methods inherited from ActiveRecord::Base

#to_yaml_properties, yaml_new

Class Method Details

.claimable_clause(as_of = db_time_now) ⇒ Object



55
56
57
# File 'app/models/delayed/job.rb', line 55

def self.claimable_clause(as_of = db_time_now)
  arel_table[:locked_at].eq(nil).or arel_table[:locked_at].lt(as_of - lock_timeout)
end

.claimed_clause(as_of = db_time_now) ⇒ Object



51
52
53
# File 'app/models/delayed/job.rb', line 51

def self.claimed_clause(as_of = db_time_now)
  arel_table[:locked_at].gteq(as_of - lock_timeout)
end

.clear_locks!(worker) ⇒ Object

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



75
76
77
# File 'app/models/delayed/job.rb', line 75

def self.clear_locks!(worker)
  claimed_by(worker).update_all(locked_by: nil, locked_at: nil)
end

.connection_configObject



231
232
233
# File 'app/models/delayed/job.rb', line 231

def self.connection_config
  connection_db_config.configuration_hash
end

.database_adapter_nameObject



226
227
228
# File 'app/models/delayed/job.rb', line 226

def self.database_adapter_name
  connection_config[:adapter]
end

.database_nameObject



222
223
224
# File 'app/models/delayed/job.rb', line 222

def self.database_name
  connection_config[:database]
end

.db_time_nowObject

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.



192
193
194
195
196
197
198
199
200
# File 'app/models/delayed/job.rb', line 192

def self.db_time_now
  if Time.zone
    Time.zone.now
  elsif default_timezone == :utc
    Time.now.utc
  else
    Time.current
  end
end

.default_timezoneObject



203
204
205
# File 'app/models/delayed/job.rb', line 203

def self.default_timezone
  ActiveRecord.default_timezone
end

.erroring_clauseObject



39
40
41
# File 'app/models/delayed/job.rb', line 39

def self.erroring_clause
  arel_table[:attempts].gt(0)
end

.future_clause(as_of = db_time_now) ⇒ Object



43
44
45
# File 'app/models/delayed/job.rb', line 43

def self.future_clause(as_of = db_time_now)
  arel_table[:run_at].gt(as_of)
end

.lock_timeoutObject



70
71
72
# File 'app/models/delayed/job.rb', line 70

def self.lock_timeout
  Worker.max_run_time + REENQUEUE_BUFFER
end

.pending_clause(as_of = db_time_now) ⇒ Object



47
48
49
# File 'app/models/delayed/job.rb', line 47

def self.pending_clause(as_of = db_time_now)
  arel_table[:run_at].lteq(as_of)
end

.reserve(worker, as_of = db_time_now) ⇒ Object



79
80
81
82
83
# File 'app/models/delayed/job.rb', line 79

def self.reserve(worker, as_of = db_time_now)
  ActiveSupport::Notifications.instrument('delayed.worker.reserve_jobs', worker_tags(worker)) do
    reserve_with_scope(claimable_by(worker, as_of), worker, as_of)
  end
end

.reserve_with_scope(ready_scope, worker, now) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'app/models/delayed/job.rb', line 85

def self.reserve_with_scope(ready_scope, worker, now)
  case connection.adapter_name
    when "PostgreSQL", "PostGIS"
      reserve_with_scope_using_optimized_postgres(ready_scope, worker, now)
    when "MySQL", "Mysql2"
      reserve_with_scope_using_optimized_mysql(ready_scope, worker, now)
    when "MSSQL", "Teradata"
      reserve_with_scope_using_optimized_mssql(ready_scope, worker, now)
    # Fallback for unknown / other DBMS
    else
      reserve_with_scope_using_default_sql(ready_scope, worker, now)
  end
end

.reserve_with_scope_using_default_sql(ready_scope, worker, now) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'app/models/delayed/job.rb', line 99

def self.reserve_with_scope_using_default_sql(ready_scope, worker, now)
  # This is our old fashion, tried and true, but possibly slower lookup
  # Instead of reading the entire job record for our detect loop, we select only the id,
  # and only read the full job record after we've successfully locked the job.
  # This can have a noticable impact on large read_ahead configurations and large payload jobs.
  attrs = { locked_at: now, locked_by: worker.name }

  jobs = []
  ready_scope.limit(worker.read_ahead).select(:id).each do |job|
    break if jobs.count >= worker.max_claims
    next unless ready_scope.where(id: job.id).update_all(attrs) == 1

    jobs << job.reload
  end

  jobs
end

.reserve_with_scope_using_optimized_mssql(ready_scope, worker, now) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'app/models/delayed/job.rb', line 174

def self.reserve_with_scope_using_optimized_mssql(ready_scope, worker, now)
  # The MSSQL driver doesn't generate a limit clause when update_all
  # is called directly
  subsubquery_sql = ready_scope.limit(1).to_sql
  # select("id") doesn't generate a subquery, so force a subquery
  subquery_sql = "SELECT id FROM (#{subsubquery_sql}) AS x"
  quoted_table_name = connection.quote_table_name(table_name)
  sql = "UPDATE #{quoted_table_name} SET locked_at = ?, locked_by = ? WHERE id IN (#{subquery_sql})"
  count = connection.execute(sanitize_sql([sql, now, worker.name]))
  return [] if count.zero?

  # MSSQL JDBC doesn't support OUTPUT INSERTED.* for returning a result set, so query locked row
  where(locked_at: now, locked_by: worker.name, failed_at: nil)
end

.reserve_with_scope_using_optimized_mysql(ready_scope, worker, now) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'app/models/delayed/job.rb', line 138

def self.reserve_with_scope_using_optimized_mysql(ready_scope, worker, now)
  # Removing the millisecond precision from now(time object)
  # MySQL 5.6.4 onwards millisecond precision exists, but the
  # datetime object created doesn't have precision, so discarded
  # while updating. But during the where clause, for mysql(>=5.6.4),
  # it queries with precision as well. So removing the precision
  now = now.change(usec: 0)
  # Despite MySQL's support of UPDATE...LIMIT, it has an optimizer bug
  # that results in filesorts rather than index scans, which is very
  # expensive with a large number of jobs in the table:
  # http://bugs.mysql.com/bug.php?id=74049
  # The PostgreSQL and MSSQL reserve strategies, while valid syntax in
  # MySQL, result in deadlocks so we use a SELECT then UPDATE strategy
  # that is more likely to false-negative when attempting to reserve
  # jobs in parallel but doesn't rely on subselects or transactions.

  # Also, we are fetching multiple candidate_jobs at a time to try to
  # avoid the situation where multiple workers try to grab the same
  # job at the same time. That previously had caused poor performance
  # since ready_scope.where(id: job.id) would return nothing even
  # though there was a large number of jobs on the queue.
  attrs = { locked_at: now, locked_by: worker.name }

  jobs = []
  ready_scope.limit(worker.read_ahead).each do |job|
    break if jobs.count >= worker.max_claims
    next unless ready_scope.where(id: job.id).update_all(attrs) == 1

    job.assign_attributes(attrs)
    job.send(:changes_applied)
    jobs << job
  end

  jobs
end

.reserve_with_scope_using_optimized_postgres(ready_scope, worker, now) ⇒ Object

rubocop:disable Metrics/AbcSize



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'app/models/delayed/job.rb', line 117

def self.reserve_with_scope_using_optimized_postgres(ready_scope, worker, now) # rubocop:disable Metrics/AbcSize
  # Custom SQL required for PostgreSQL because postgres does not support UPDATE...LIMIT
  # This locks the single record 'FOR UPDATE' in the subquery
  # http://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-FOR-UPDATE-SHARE
  # Note: active_record would attempt to generate UPDATE...LIMIT like
  # SQL for Postgres if we use a .limit() filter, but it would not
  # use 'FOR UPDATE' and we would have many locking conflicts
  table = connection.quote_table_name(table_name)

  # Rather than relying on a primary key, we use "WHERE ctid =", resulting in a fast 'Tid Scan'.
  if worker.max_claims > 1
    subquery = ready_scope.limit(worker.max_claims).lock("FOR UPDATE SKIP LOCKED").select("ctid").to_sql
    sql = "UPDATE #{table} SET locked_at = ?, locked_by = ? WHERE ctid = ANY (ARRAY (#{subquery})) RETURNING *"
  else
    subquery = ready_scope.limit(1).lock("FOR UPDATE SKIP LOCKED").select("ctid").to_sql
    sql = "UPDATE #{table} SET locked_at = ?, locked_by = ? WHERE ctid = (#{subquery}) RETURNING *"
  end

  find_by_sql([sql, now, worker.name]).sort_by(&:priority)
end

.set_delayed_job_table_nameObject



63
64
65
66
# File 'app/models/delayed/job.rb', line 63

def self.set_delayed_job_table_name
  delayed_job_table_name = "#{::ActiveRecord::Base.table_name_prefix}delayed_jobs"
  self.table_name = delayed_job_table_name
end

.worker_tags(worker) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'app/models/delayed/job.rb', line 208

def self.worker_tags(worker)
  {
    min_priority: worker.min_priority,
    max_priority: worker.max_priority,
    max_claims: worker.max_claims,
    read_ahead: worker.read_ahead,
    queues: worker.queues,
    table: table_name,
    database: database_name,
    database_adapter: database_adapter_name,
    worker: worker,
  }
end

Instance Method Details

#ageObject



265
266
267
# File 'app/models/delayed/job.rb', line 265

def age
  [(locked_at || self.class.db_time_now) - run_at, 0].max
end

#age_alert?Boolean

Returns:

  • (Boolean)


273
274
275
# File 'app/models/delayed/job.rb', line 273

def age_alert?
  alert_age&.<= age
end

#alert_ageObject



241
242
243
244
245
246
247
# File 'app/models/delayed/job.rb', line 241

def alert_age
  if payload_object.respond_to?(:alert_age)
    payload_object.alert_age
  else
    priority.alert_age
  end
end

#alert_attemptsObject



257
258
259
260
261
262
263
# File 'app/models/delayed/job.rb', line 257

def alert_attempts
  if payload_object.respond_to?(:alert_attempts)
    payload_object.alert_attempts
  else
    priority.alert_attempts
  end
end

#alert_run_timeObject



249
250
251
252
253
254
255
# File 'app/models/delayed/job.rb', line 249

def alert_run_time
  if payload_object.respond_to?(:alert_run_time)
    payload_object.alert_run_time
  else
    priority.alert_run_time
  end
end

#attempts_alert?Boolean

Returns:

  • (Boolean)


281
282
283
# File 'app/models/delayed/job.rb', line 281

def attempts_alert?
  alert_attempts&.<= attempts
end

#reload(*args) ⇒ Object



236
237
238
239
# File 'app/models/delayed/job.rb', line 236

def reload(*args)
  reset
  super
end

#run_timeObject



269
270
271
# File 'app/models/delayed/job.rb', line 269

def run_time
  self.class.db_time_now - locked_at if locked_at
end

#run_time_alert?Boolean

Returns:

  • (Boolean)


277
278
279
# File 'app/models/delayed/job.rb', line 277

def run_time_alert?
  alert_run_time&.<= run_time if run_time # locked_at may be `nil` if `delay_jobs` is false
end