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.



73
74
75
# File 'app/models/delayed/job.rb', line 73

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

.connection_configObject



229
230
231
# File 'app/models/delayed/job.rb', line 229

def self.connection_config
  connection_db_config.configuration_hash
end

.database_adapter_nameObject



224
225
226
# File 'app/models/delayed/job.rb', line 224

def self.database_adapter_name
  connection_config[:adapter]
end

.database_nameObject



220
221
222
# File 'app/models/delayed/job.rb', line 220

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.



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

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



201
202
203
# File 'app/models/delayed/job.rb', line 201

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



68
69
70
# File 'app/models/delayed/job.rb', line 68

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



77
78
79
80
81
# File 'app/models/delayed/job.rb', line 77

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



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

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



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

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



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

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



136
137
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
# File 'app/models/delayed/job.rb', line 136

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



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

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



61
62
63
64
# File 'app/models/delayed/job.rb', line 61

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



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

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



263
264
265
# File 'app/models/delayed/job.rb', line 263

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

#age_alert?Boolean

Returns:

  • (Boolean)


271
272
273
# File 'app/models/delayed/job.rb', line 271

def age_alert?
  alert_age&.<= age
end

#alert_ageObject



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

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

#alert_attemptsObject



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

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

#alert_run_timeObject



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

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)


279
280
281
# File 'app/models/delayed/job.rb', line 279

def attempts_alert?
  alert_attempts&.<= attempts
end

#reload(*args) ⇒ Object



234
235
236
237
# File 'app/models/delayed/job.rb', line 234

def reload(*args)
  reset
  super
end

#run_timeObject



267
268
269
# File 'app/models/delayed/job.rb', line 267

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

#run_time_alert?Boolean

Returns:

  • (Boolean)


275
276
277
# File 'app/models/delayed/job.rb', line 275

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