Class: Delayed::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/delayed/worker.rb

Overview

rubocop:disable ClassLength

Constant Summary collapse

DEFAULT_LOG_LEVEL =
'info'.freeze
DEFAULT_SLEEP_DELAY =
5
DEFAULT_MAX_ATTEMPTS =
25
DEFAULT_MAX_RUN_TIME =
4.hours
DEFAULT_DEFAULT_PRIORITY =
0
DEFAULT_DELAY_JOBS =
true
DEFAULT_QUEUES =
[].freeze
DEFAULT_QUEUE_ATTRIBUTES =
[].freeze
DEFAULT_READ_AHEAD =
5

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Worker

Returns a new instance of Worker


125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/delayed/worker.rb', line 125

def initialize(options = {})
  @quiet = options.key?(:quiet) ? options[:quiet] : true
  @failed_reserve_count = 0

  [:min_priority, :max_priority, :sleep_delay, :read_ahead, :queues, :exit_on_complete].each do |option|
    self.class.send("#{option}=", options[option]) if options.key?(option)
  end

  # Reset lifecycle on the offhand chance that something lazily
  # triggered its creation before all plugins had been registered.
  self.class.setup_lifecycle
end

Instance Attribute Details

#nameObject

Every worker has a unique name which by default is the pid of the process. There are some advantages to overriding this with something which survives worker restarts: Workers can safely resume working on tasks which are locked by themselves. The worker will assume that it crashed before.


142
143
144
145
# File 'lib/delayed/worker.rb', line 142

def name
  return @name unless @name.nil?
  "#{@name_prefix}host:#{Socket.gethostname} pid:#{Process.pid}" rescue "#{@name_prefix}pid:#{Process.pid}"
end

#name_prefixObject

name_prefix is ignored if name is set directly


31
32
33
# File 'lib/delayed/worker.rb', line 31

def name_prefix
  @name_prefix
end

Class Method Details

.after_forkObject


89
90
91
92
93
94
95
96
97
98
99
# File 'lib/delayed/worker.rb', line 89

def self.after_fork
  # Re-open file handles
  @files_to_reopen.each do |file|
    begin
      file.reopen file.path, 'a+'
      file.sync = true
    rescue ::Exception # rubocop:disable HandleExceptions, RescueException
    end
  end
  backend.after_fork
end

.backend=(backend) ⇒ Object


64
65
66
67
68
69
70
71
72
# File 'lib/delayed/worker.rb', line 64

def self.backend=(backend)
  if backend.is_a? Symbol
    require "delayed/serialization/#{backend}"
    require "delayed/backend/#{backend}"
    backend = "Delayed::Backend::#{backend.to_s.classify}::Job".constantize
  end
  @@backend = backend # rubocop:disable ClassVars
  silence_warnings { ::Delayed.const_set(:Job, backend) }
end

.before_forkObject


78
79
80
81
82
83
84
85
86
87
# File 'lib/delayed/worker.rb', line 78

def self.before_fork
  unless @files_to_reopen
    @files_to_reopen = []
    ObjectSpace.each_object(File) do |file|
      @files_to_reopen << file unless file.closed?
    end
  end

  backend.before_fork
end

.delay_job?(job) ⇒ Boolean

Returns:

  • (Boolean)

117
118
119
120
121
122
123
# File 'lib/delayed/worker.rb', line 117

def self.delay_job?(job)
  if delay_jobs.is_a?(Proc)
    delay_jobs.arity == 1 ? delay_jobs.call(job) : delay_jobs.call
  else
    delay_jobs
  end
end

.guess_backendObject


74
75
76
# File 'lib/delayed/worker.rb', line 74

def self.guess_backend
  warn '[DEPRECATION] guess_backend is deprecated. Please remove it from your code.'
end

.lifecycleObject


101
102
103
104
105
106
# File 'lib/delayed/worker.rb', line 101

def self.lifecycle
  # In case a worker has not been set up, job enqueueing needs a lifecycle.
  setup_lifecycle unless @lifecycle

  @lifecycle
end

.reload_app?Boolean

Returns:

  • (Boolean)

113
114
115
# File 'lib/delayed/worker.rb', line 113

def self.reload_app?
  defined?(ActionDispatch::Reloader) && Rails.application.config.cache_classes == false
end

.resetObject


33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/delayed/worker.rb', line 33

def self.reset
  self.default_log_level = DEFAULT_LOG_LEVEL
  self.sleep_delay       = DEFAULT_SLEEP_DELAY
  self.max_attempts      = DEFAULT_MAX_ATTEMPTS
  self.max_run_time      = DEFAULT_MAX_RUN_TIME
  self.default_priority  = DEFAULT_DEFAULT_PRIORITY
  self.delay_jobs        = DEFAULT_DELAY_JOBS
  self.queues            = DEFAULT_QUEUES
  self.queue_attributes  = DEFAULT_QUEUE_ATTRIBUTES
  self.read_ahead        = DEFAULT_READ_AHEAD
  @lifecycle             = nil
end

.setup_lifecycleObject


108
109
110
111
# File 'lib/delayed/worker.rb', line 108

def self.setup_lifecycle
  @lifecycle = Delayed::Lifecycle.new
  plugins.each { |klass| klass.new }
end

Instance Method Details

#failed(job) ⇒ Object


252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/delayed/worker.rb', line 252

def failed(job)
  self.class.lifecycle.run_callbacks(:failure, self, job) do
    begin
      job.hook(:failure)
    rescue => error
      say "Error when running failure callback: #{error}", 'error'
      say error.backtrace.join("\n"), 'error'
    ensure
      job.destroy_failed_jobs? ? job.destroy : job.fail!
    end
  end
end

#job_say(job, text, level = default_log_level) ⇒ Object


265
266
267
268
# File 'lib/delayed/worker.rb', line 265

def job_say(job, text, level = default_log_level)
  text = "Job #{job.name} (id=#{job.id}) #{text}"
  say text, level
end

#max_attempts(job) ⇒ Object


281
282
283
# File 'lib/delayed/worker.rb', line 281

def max_attempts(job)
  job.max_attempts || self.class.max_attempts
end

#max_run_time(job) ⇒ Object


285
286
287
# File 'lib/delayed/worker.rb', line 285

def max_run_time(job)
  job.max_run_time || self.class.max_run_time
end

#reschedule(job, time = nil) ⇒ Object

Reschedule the job in the future (when a job fails). Uses an exponential scale depending on the number of failed attempts.


240
241
242
243
244
245
246
247
248
249
250
# File 'lib/delayed/worker.rb', line 240

def reschedule(job, time = nil)
  if (job.attempts += 1) < max_attempts(job)
    time ||= job.reschedule_at
    job.run_at = time
    job.unlock
    job.save!
  else
    job_say job, "REMOVED permanently because of #{job.attempts} consecutive failures", 'error'
    failed(job)
  end
end

#run(job) ⇒ Object


222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/delayed/worker.rb', line 222

def run(job)
  job_say job, 'RUNNING'
  runtime = Benchmark.realtime do
    Timeout.timeout(max_run_time(job).to_i, WorkerTimeout) { job.invoke_job }
    job.destroy
  end
  job_say job, format('COMPLETED after %.4f', runtime)
  return true # did work
rescue DeserializationError => error
  job.error = error
  failed(job)
rescue Exception => error # rubocop:disable RescueException
  self.class.lifecycle.run_callbacks(:error, self, job) { handle_failed_job(job, error) }
  return false # work failed
end

#say(text, level = default_log_level) ⇒ Object


270
271
272
273
274
275
276
277
278
279
# File 'lib/delayed/worker.rb', line 270

def say(text, level = default_log_level)
  text = "[Worker(#{name})] #{text}"
  puts text unless @quiet
  return unless logger
  # TODO: Deprecate use of Fixnum log levels
  unless level.is_a?(String)
    level = Logger::Severity.constants.detect { |i| Logger::Severity.const_get(i) == level }.to_s.downcase
  end
  logger.send(level, "#{Time.now.strftime('%FT%T%z')}: #{text}")
end

#startObject

rubocop:disable CyclomaticComplexity, PerceivedComplexity


151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/delayed/worker.rb', line 151

def start # rubocop:disable CyclomaticComplexity, PerceivedComplexity
  trap('TERM') do
    Thread.new { say 'Exiting...' }
    stop
    raise SignalException, 'TERM' if self.class.raise_signal_exceptions
  end

  trap('INT') do
    Thread.new { say 'Exiting...' }
    stop
    raise SignalException, 'INT' if self.class.raise_signal_exceptions && self.class.raise_signal_exceptions != :term
  end

  say 'Starting job worker'

  self.class.lifecycle.run_callbacks(:execute, self) do
    loop do
      self.class.lifecycle.run_callbacks(:loop, self) do
        @realtime = Benchmark.realtime do
          @result = work_off
        end
      end

      count = @result[0] + @result[1]

      if count.zero?
        if self.class.exit_on_complete
          say 'No more jobs available. Exiting'
          break
        elsif !stop?
          sleep(self.class.sleep_delay)
          reload!
        end
      else
        say format("#{count} jobs processed at %.4f j/s, %d failed", count / @realtime, @result.last)
      end

      break if stop?
    end
  end
end

#stopObject


193
194
195
# File 'lib/delayed/worker.rb', line 193

def stop
  @exit = true
end

#stop?Boolean

Returns:

  • (Boolean)

197
198
199
# File 'lib/delayed/worker.rb', line 197

def stop?
  !!@exit
end

#work_off(num = 100) ⇒ Object

Do num jobs and return stats on success/failure. Exit early if interrupted.


203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/delayed/worker.rb', line 203

def work_off(num = 100)
  success = 0
  failure = 0

  num.times do
    case reserve_and_run_one_job
    when true
      success += 1
    when false
      failure += 1
    else
      break # leave if no work could be done
    end
    break if stop? # leave if we're exiting
  end

  [success, failure]
end