moneypools-delayed_job 1.8.4
Sign up to get free protection for your applications and to get access to all the features.
- data/.gitignore +1 -0
- data/MIT-LICENSE +20 -0
- data/README.textile +195 -0
- data/Rakefile +39 -0
- data/VERSION +1 -0
- data/contrib/delayed_job.monitrc +14 -0
- data/delayed_job.gemspec +94 -0
- data/generators/delayed_job/delayed_job_generator.rb +22 -0
- data/generators/delayed_job/templates/migration.rb +21 -0
- data/generators/delayed_job/templates/script +5 -0
- data/init.rb +1 -0
- data/lib/delayed/backend/active_record.rb +84 -0
- data/lib/delayed/backend/base.rb +98 -0
- data/lib/delayed/backend/mongo_mapper.rb +104 -0
- data/lib/delayed/command.rb +77 -0
- data/lib/delayed/message_sending.rb +22 -0
- data/lib/delayed/performable_method.rb +62 -0
- data/lib/delayed/recipes.rb +31 -0
- data/lib/delayed/tasks.rb +15 -0
- data/lib/delayed/worker.rb +165 -0
- data/lib/delayed_job.rb +22 -0
- data/recipes/delayed_job.rb +1 -0
- data/spec/backend/active_record_job_spec.rb +41 -0
- data/spec/backend/mongo_mapper_job_spec.rb +59 -0
- data/spec/backend/shared_backend_spec.rb +244 -0
- data/spec/delayed_method_spec.rb +59 -0
- data/spec/performable_method_spec.rb +42 -0
- data/spec/sample_jobs.rb +21 -0
- data/spec/setup/active_record.rb +33 -0
- data/spec/setup/mongo_mapper.rb +13 -0
- data/spec/spec_helper.rb +33 -0
- data/spec/story_spec.rb +17 -0
- data/spec/worker_spec.rb +178 -0
- data/tasks/jobs.rake +1 -0
- metadata +144 -0
@@ -0,0 +1,98 @@
|
|
1
|
+
module Delayed
|
2
|
+
module Backend
|
3
|
+
class DeserializationError < StandardError
|
4
|
+
end
|
5
|
+
|
6
|
+
module Base
|
7
|
+
def self.included(base)
|
8
|
+
base.extend ClassMethods
|
9
|
+
end
|
10
|
+
|
11
|
+
module ClassMethods
|
12
|
+
# Add a job to the queue
|
13
|
+
def enqueue(*args)
|
14
|
+
object = args.shift
|
15
|
+
unless object.respond_to?(:perform)
|
16
|
+
raise ArgumentError, 'Cannot enqueue items which do not respond to perform'
|
17
|
+
end
|
18
|
+
|
19
|
+
priority = args.first || 0
|
20
|
+
run_at = args[1]
|
21
|
+
self.create(:payload_object => object, :priority => priority.to_i, :run_at => run_at)
|
22
|
+
end
|
23
|
+
end
|
24
|
+
|
25
|
+
ParseObjectFromYaml = /\!ruby\/\w+\:([^\s]+)/
|
26
|
+
|
27
|
+
def failed?
|
28
|
+
failed_at
|
29
|
+
end
|
30
|
+
alias_method :failed, :failed?
|
31
|
+
|
32
|
+
def payload_object
|
33
|
+
@payload_object ||= deserialize(self['handler'])
|
34
|
+
end
|
35
|
+
|
36
|
+
def name
|
37
|
+
@name ||= begin
|
38
|
+
payload = payload_object
|
39
|
+
if payload.respond_to?(:display_name)
|
40
|
+
payload.display_name
|
41
|
+
else
|
42
|
+
payload.class.name
|
43
|
+
end
|
44
|
+
end
|
45
|
+
end
|
46
|
+
|
47
|
+
def payload_object=(object)
|
48
|
+
self['handler'] = object.to_yaml
|
49
|
+
end
|
50
|
+
|
51
|
+
# Moved into its own method so that new_relic can trace it.
|
52
|
+
def invoke_job
|
53
|
+
payload_object.perform
|
54
|
+
end
|
55
|
+
|
56
|
+
# Unlock this job (note: not saved to DB)
|
57
|
+
def unlock
|
58
|
+
self.locked_at = nil
|
59
|
+
self.locked_by = nil
|
60
|
+
end
|
61
|
+
|
62
|
+
private
|
63
|
+
|
64
|
+
def deserialize(source)
|
65
|
+
handler = YAML.load(source) rescue nil
|
66
|
+
|
67
|
+
unless handler.respond_to?(:perform)
|
68
|
+
if handler.nil? && source =~ ParseObjectFromYaml
|
69
|
+
handler_class = $1
|
70
|
+
end
|
71
|
+
attempt_to_load(handler_class || handler.class)
|
72
|
+
handler = YAML.load(source)
|
73
|
+
end
|
74
|
+
|
75
|
+
return handler if handler.respond_to?(:perform)
|
76
|
+
|
77
|
+
raise DeserializationError,
|
78
|
+
'Job failed to load: Unknown handler. Try to manually require the appropriate file.'
|
79
|
+
rescue TypeError, LoadError, NameError => e
|
80
|
+
raise DeserializationError,
|
81
|
+
"Job failed to load: #{e.message}. Try to manually require the required file."
|
82
|
+
end
|
83
|
+
|
84
|
+
# Constantize the object so that ActiveSupport can attempt
|
85
|
+
# its auto loading magic. Will raise LoadError if not successful.
|
86
|
+
def attempt_to_load(klass)
|
87
|
+
klass.constantize
|
88
|
+
end
|
89
|
+
|
90
|
+
protected
|
91
|
+
|
92
|
+
def before_save
|
93
|
+
self.run_at ||= self.class.db_time_now
|
94
|
+
end
|
95
|
+
|
96
|
+
end
|
97
|
+
end
|
98
|
+
end
|
@@ -0,0 +1,104 @@
|
|
1
|
+
require 'mongo_mapper'
|
2
|
+
|
3
|
+
module ::MongoMapper
|
4
|
+
module Document
|
5
|
+
module ClassMethods
|
6
|
+
def load_for_delayed_job(id)
|
7
|
+
find!(id)
|
8
|
+
end
|
9
|
+
end
|
10
|
+
|
11
|
+
module InstanceMethods
|
12
|
+
def dump_for_delayed_job
|
13
|
+
"#{self.class};#{id}"
|
14
|
+
end
|
15
|
+
end
|
16
|
+
end
|
17
|
+
end
|
18
|
+
|
19
|
+
module Delayed
|
20
|
+
module Backend
|
21
|
+
module MongoMapper
|
22
|
+
class Job
|
23
|
+
include ::MongoMapper::Document
|
24
|
+
include Delayed::Backend::Base
|
25
|
+
set_collection_name 'delayed_jobs'
|
26
|
+
|
27
|
+
key :priority, Integer, :default => 0
|
28
|
+
key :attempts, Integer, :default => 0
|
29
|
+
key :handler, String
|
30
|
+
key :run_at, Time
|
31
|
+
key :locked_at, Time
|
32
|
+
key :locked_by, String
|
33
|
+
key :failed_at, Time
|
34
|
+
key :last_error, String
|
35
|
+
timestamps!
|
36
|
+
|
37
|
+
before_save :set_default_run_at
|
38
|
+
|
39
|
+
def self.db_time_now
|
40
|
+
::MongoMapper.time_class.now.utc
|
41
|
+
end
|
42
|
+
|
43
|
+
def self.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time)
|
44
|
+
right_now = db_time_now
|
45
|
+
|
46
|
+
conditions = {
|
47
|
+
:run_at => {"$lte" => right_now},
|
48
|
+
:limit => limit,
|
49
|
+
:failed_at => nil,
|
50
|
+
:sort => [['priority', 1], ['run_at', 1]]
|
51
|
+
}
|
52
|
+
|
53
|
+
where = "this.locked_at == null || this.locked_at < #{make_date(right_now - max_run_time)}"
|
54
|
+
|
55
|
+
(conditions[:priority] ||= {})['$gte'] = Worker.min_priority if Worker.min_priority
|
56
|
+
(conditions[:priority] ||= {})['$lte'] = Worker.max_priority if Worker.max_priority
|
57
|
+
|
58
|
+
results = all(conditions.merge(:locked_by => worker_name))
|
59
|
+
results += all(conditions.merge('$where' => where)) if results.size < limit
|
60
|
+
results
|
61
|
+
end
|
62
|
+
|
63
|
+
# When a worker is exiting, make sure we don't have any locked jobs.
|
64
|
+
def self.clear_locks!(worker_name)
|
65
|
+
collection.update({:locked_by => worker_name}, {"$set" => {:locked_at => nil, :locked_by => nil}}, :multi => true)
|
66
|
+
end
|
67
|
+
|
68
|
+
# Lock this job for this worker.
|
69
|
+
# Returns true if we have the lock, false otherwise.
|
70
|
+
def lock_exclusively!(max_run_time, worker = worker_name)
|
71
|
+
right_now = self.class.db_time_now
|
72
|
+
overtime = right_now - max_run_time.to_i
|
73
|
+
|
74
|
+
query = "this.locked_at == null || this.locked_at < #{make_date(overtime)} || this.locked_by == #{worker.to_json}"
|
75
|
+
conditions = {:_id => id, :run_at => {"$lte" => right_now}, "$where" => query}
|
76
|
+
|
77
|
+
collection.update(conditions, {"$set" => {:locked_at => right_now, :locked_by => worker}})
|
78
|
+
affected_rows = collection.find({:_id => id, :locked_by => worker}).count
|
79
|
+
if affected_rows == 1
|
80
|
+
self.locked_at = right_now
|
81
|
+
self.locked_by = worker
|
82
|
+
return true
|
83
|
+
else
|
84
|
+
return false
|
85
|
+
end
|
86
|
+
end
|
87
|
+
|
88
|
+
private
|
89
|
+
|
90
|
+
def self.make_date(date_or_seconds)
|
91
|
+
"new Date(#{date_or_seconds.to_f * 1000})"
|
92
|
+
end
|
93
|
+
|
94
|
+
def make_date(date)
|
95
|
+
self.class.make_date(date)
|
96
|
+
end
|
97
|
+
|
98
|
+
def set_default_run_at
|
99
|
+
self.run_at ||= self.class.db_time_now
|
100
|
+
end
|
101
|
+
end
|
102
|
+
end
|
103
|
+
end
|
104
|
+
end
|
@@ -0,0 +1,77 @@
|
|
1
|
+
require 'rubygems'
|
2
|
+
require 'daemons'
|
3
|
+
require 'optparse'
|
4
|
+
|
5
|
+
module Delayed
|
6
|
+
class Command
|
7
|
+
attr_accessor :worker_count
|
8
|
+
|
9
|
+
def initialize(args)
|
10
|
+
@files_to_reopen = []
|
11
|
+
@options = {:quiet => true}
|
12
|
+
|
13
|
+
@worker_count = 1
|
14
|
+
|
15
|
+
opts = OptionParser.new do |opts|
|
16
|
+
opts.banner = "Usage: #{File.basename($0)} [options] start|stop|restart|run"
|
17
|
+
|
18
|
+
opts.on('-h', '--help', 'Show this message') do
|
19
|
+
puts opts
|
20
|
+
exit 1
|
21
|
+
end
|
22
|
+
opts.on('-e', '--environment=NAME', 'Specifies the environment to run this delayed jobs under (test/development/production).') do |e|
|
23
|
+
STDERR.puts "The -e/--environment option has been deprecated and has no effect. Use RAILS_ENV and see http://github.com/collectiveidea/delayed_job/issues/#issue/7"
|
24
|
+
end
|
25
|
+
opts.on('--min-priority N', 'Minimum priority of jobs to run.') do |n|
|
26
|
+
@options[:min_priority] = n
|
27
|
+
end
|
28
|
+
opts.on('--max-priority N', 'Maximum priority of jobs to run.') do |n|
|
29
|
+
@options[:max_priority] = n
|
30
|
+
end
|
31
|
+
opts.on('-n', '--number_of_workers=workers', "Number of unique workers to spawn") do |worker_count|
|
32
|
+
@worker_count = worker_count.to_i rescue 1
|
33
|
+
end
|
34
|
+
end
|
35
|
+
@args = opts.parse!(args)
|
36
|
+
end
|
37
|
+
|
38
|
+
def daemonize
|
39
|
+
ObjectSpace.each_object(File) do |file|
|
40
|
+
@files_to_reopen << file unless file.closed?
|
41
|
+
end
|
42
|
+
|
43
|
+
worker_count.times do |worker_index|
|
44
|
+
process_name = worker_count == 1 ? "delayed_job" : "delayed_job.#{worker_index}"
|
45
|
+
Daemons.run_proc(process_name, :dir => "#{RAILS_ROOT}/tmp/pids", :dir_mode => :normal, :ARGV => @args) do |*args|
|
46
|
+
run process_name
|
47
|
+
end
|
48
|
+
end
|
49
|
+
end
|
50
|
+
|
51
|
+
def run(worker_name = nil)
|
52
|
+
Dir.chdir(RAILS_ROOT)
|
53
|
+
|
54
|
+
# Re-open file handles
|
55
|
+
@files_to_reopen.each do |file|
|
56
|
+
begin
|
57
|
+
file.reopen File.join(RAILS_ROOT, 'log', 'delayed_job.log'), 'a+'
|
58
|
+
file.sync = true
|
59
|
+
rescue ::Exception
|
60
|
+
end
|
61
|
+
end
|
62
|
+
|
63
|
+
Delayed::Worker.logger = Rails.logger
|
64
|
+
Delayed::Worker.logger.auto_flushing = true
|
65
|
+
ActiveRecord::Base.connection.reconnect!
|
66
|
+
|
67
|
+
worker = Delayed::Worker.new(@options)
|
68
|
+
worker.name_prefix = "#{worker_name} "
|
69
|
+
worker.start
|
70
|
+
rescue => e
|
71
|
+
Rails.logger.fatal e
|
72
|
+
STDERR.puts e.message
|
73
|
+
exit 1
|
74
|
+
end
|
75
|
+
|
76
|
+
end
|
77
|
+
end
|
@@ -0,0 +1,22 @@
|
|
1
|
+
module Delayed
|
2
|
+
module MessageSending
|
3
|
+
def send_later(method, *args)
|
4
|
+
Delayed::Job.enqueue Delayed::PerformableMethod.new(self, method.to_sym, args)
|
5
|
+
end
|
6
|
+
|
7
|
+
def send_at(time, method, *args)
|
8
|
+
Delayed::Job.enqueue(Delayed::PerformableMethod.new(self, method.to_sym, args), 0, time)
|
9
|
+
end
|
10
|
+
|
11
|
+
module ClassMethods
|
12
|
+
def handle_asynchronously(method)
|
13
|
+
aliased_method, punctuation = method.to_s.sub(/([?!=])$/, ''), $1
|
14
|
+
with_method, without_method = "#{aliased_method}_with_send_later#{punctuation}", "#{aliased_method}_without_send_later#{punctuation}"
|
15
|
+
define_method(with_method) do |*args|
|
16
|
+
send_later(without_method, *args)
|
17
|
+
end
|
18
|
+
alias_method_chain method, :send_later
|
19
|
+
end
|
20
|
+
end
|
21
|
+
end
|
22
|
+
end
|
@@ -0,0 +1,62 @@
|
|
1
|
+
class Class
|
2
|
+
def load_for_delayed_job(arg)
|
3
|
+
self
|
4
|
+
end
|
5
|
+
|
6
|
+
def dump_for_delayed_job
|
7
|
+
name
|
8
|
+
end
|
9
|
+
end
|
10
|
+
|
11
|
+
module Delayed
|
12
|
+
class PerformableMethod < Struct.new(:object, :method, :args)
|
13
|
+
STRING_FORMAT = /^LOAD\;([A-Z][\w\:]+)(?:\;(\w+))?$/
|
14
|
+
|
15
|
+
class LoadError < StandardError
|
16
|
+
end
|
17
|
+
|
18
|
+
def initialize(object, method, args)
|
19
|
+
raise NoMethodError, "undefined method `#{method}' for #{object.inspect}" unless object.respond_to?(method)
|
20
|
+
|
21
|
+
self.object = dump(object)
|
22
|
+
self.args = args.map { |a| dump(a) }
|
23
|
+
self.method = method.to_sym
|
24
|
+
end
|
25
|
+
|
26
|
+
def display_name
|
27
|
+
if STRING_FORMAT === object
|
28
|
+
"#{$1}#{$2 ? '#' : '.'}#{method}"
|
29
|
+
else
|
30
|
+
"#{object.class}##{method}"
|
31
|
+
end
|
32
|
+
end
|
33
|
+
|
34
|
+
def perform
|
35
|
+
load(object).send(method, *args.map{|a| load(a)})
|
36
|
+
rescue PerformableMethod::LoadError
|
37
|
+
# We cannot do anything about objects that can't be loaded
|
38
|
+
true
|
39
|
+
end
|
40
|
+
|
41
|
+
private
|
42
|
+
|
43
|
+
def load(obj)
|
44
|
+
if STRING_FORMAT === obj
|
45
|
+
$1.constantize.load_for_delayed_job($2)
|
46
|
+
else
|
47
|
+
obj
|
48
|
+
end
|
49
|
+
rescue => e
|
50
|
+
Delayed::Worker.logger.warn "Could not load object for job: #{e.message}"
|
51
|
+
raise PerformableMethod::LoadError
|
52
|
+
end
|
53
|
+
|
54
|
+
def dump(obj)
|
55
|
+
if obj.respond_to?(:dump_for_delayed_job)
|
56
|
+
"LOAD;#{obj.dump_for_delayed_job}"
|
57
|
+
else
|
58
|
+
obj
|
59
|
+
end
|
60
|
+
end
|
61
|
+
end
|
62
|
+
end
|
@@ -0,0 +1,31 @@
|
|
1
|
+
# Capistrano Recipes for managing delayed_job
|
2
|
+
#
|
3
|
+
# Add these callbacks to have the delayed_job process restart when the server
|
4
|
+
# is restarted:
|
5
|
+
#
|
6
|
+
# after "deploy:stop", "delayed_job:stop"
|
7
|
+
# after "deploy:start", "delayed_job:start"
|
8
|
+
# after "deploy:restart", "delayed_job:restart"
|
9
|
+
|
10
|
+
Capistrano::Configuration.instance.load do
|
11
|
+
namespace :delayed_job do
|
12
|
+
def rails_env
|
13
|
+
fetch(:rails_env, false) ? "RAILS_ENV=#{fetch(:rails_env)}" : ''
|
14
|
+
end
|
15
|
+
|
16
|
+
desc "Stop the delayed_job process"
|
17
|
+
task :stop, :roles => :app do
|
18
|
+
run "cd #{current_path};#{rails_env} script/delayed_job stop"
|
19
|
+
end
|
20
|
+
|
21
|
+
desc "Start the delayed_job process"
|
22
|
+
task :start, :roles => :app do
|
23
|
+
run "cd #{current_path};#{rails_env} script/delayed_job start"
|
24
|
+
end
|
25
|
+
|
26
|
+
desc "Restart the delayed_job process"
|
27
|
+
task :restart, :roles => :app do
|
28
|
+
run "cd #{current_path};#{rails_env} script/delayed_job restart"
|
29
|
+
end
|
30
|
+
end
|
31
|
+
end
|
@@ -0,0 +1,15 @@
|
|
1
|
+
# Re-definitions are appended to existing tasks
|
2
|
+
task :environment
|
3
|
+
task :merb_env
|
4
|
+
|
5
|
+
namespace :jobs do
|
6
|
+
desc "Clear the delayed_job queue."
|
7
|
+
task :clear => [:merb_env, :environment] do
|
8
|
+
Delayed::Job.delete_all
|
9
|
+
end
|
10
|
+
|
11
|
+
desc "Start a delayed_job worker."
|
12
|
+
task :work => [:merb_env, :environment] do
|
13
|
+
Delayed::Worker.new(:min_priority => ENV['MIN_PRIORITY'], :max_priority => ENV['MAX_PRIORITY']).start
|
14
|
+
end
|
15
|
+
end
|
@@ -0,0 +1,165 @@
|
|
1
|
+
require 'timeout'
|
2
|
+
|
3
|
+
module Delayed
|
4
|
+
class Worker
|
5
|
+
cattr_accessor :min_priority, :max_priority, :max_attempts, :max_run_time, :sleep_delay, :logger
|
6
|
+
self.sleep_delay = 5
|
7
|
+
self.max_attempts = 25
|
8
|
+
self.max_run_time = 4.hours
|
9
|
+
|
10
|
+
# By default failed jobs are destroyed after too many attempts. If you want to keep them around
|
11
|
+
# (perhaps to inspect the reason for the failure), set this to false.
|
12
|
+
cattr_accessor :destroy_failed_jobs
|
13
|
+
self.destroy_failed_jobs = true
|
14
|
+
|
15
|
+
self.logger = if defined?(Merb::Logger)
|
16
|
+
Merb.logger
|
17
|
+
elsif defined?(RAILS_DEFAULT_LOGGER)
|
18
|
+
RAILS_DEFAULT_LOGGER
|
19
|
+
end
|
20
|
+
|
21
|
+
# name_prefix is ignored if name is set directly
|
22
|
+
attr_accessor :name_prefix
|
23
|
+
|
24
|
+
cattr_reader :backend
|
25
|
+
|
26
|
+
def self.backend=(backend)
|
27
|
+
if backend.is_a? Symbol
|
28
|
+
require "delayed/backend/#{backend}"
|
29
|
+
backend = "Delayed::Backend::#{backend.to_s.classify}::Job".constantize
|
30
|
+
end
|
31
|
+
@@backend = backend
|
32
|
+
silence_warnings { ::Delayed.const_set(:Job, backend) }
|
33
|
+
end
|
34
|
+
|
35
|
+
def initialize(options={})
|
36
|
+
@quiet = options[:quiet]
|
37
|
+
self.class.min_priority = options[:min_priority] if options.has_key?(:min_priority)
|
38
|
+
self.class.max_priority = options[:max_priority] if options.has_key?(:max_priority)
|
39
|
+
end
|
40
|
+
|
41
|
+
# Every worker has a unique name which by default is the pid of the process. There are some
|
42
|
+
# advantages to overriding this with something which survives worker retarts: Workers can#
|
43
|
+
# safely resume working on tasks which are locked by themselves. The worker will assume that
|
44
|
+
# it crashed before.
|
45
|
+
def name
|
46
|
+
return @name unless @name.nil?
|
47
|
+
"#{@name_prefix}host:#{Socket.gethostname} pid:#{Process.pid}" rescue "#{@name_prefix}pid:#{Process.pid}"
|
48
|
+
end
|
49
|
+
|
50
|
+
# Sets the name of the worker.
|
51
|
+
# Setting the name to nil will reset the default worker name
|
52
|
+
def name=(val)
|
53
|
+
@name = val
|
54
|
+
end
|
55
|
+
|
56
|
+
def start
|
57
|
+
say "*** Starting job worker #{name}"
|
58
|
+
|
59
|
+
trap('TERM') { say 'Exiting...'; $exit = true }
|
60
|
+
trap('INT') { say 'Exiting...'; $exit = true }
|
61
|
+
|
62
|
+
loop do
|
63
|
+
result = nil
|
64
|
+
|
65
|
+
realtime = Benchmark.realtime do
|
66
|
+
result = work_off
|
67
|
+
end
|
68
|
+
|
69
|
+
count = result.sum
|
70
|
+
|
71
|
+
break if $exit
|
72
|
+
|
73
|
+
if count.zero?
|
74
|
+
sleep(@@sleep_delay)
|
75
|
+
else
|
76
|
+
say "#{count} jobs processed at %.4f j/s, %d failed ..." % [count / realtime, result.last]
|
77
|
+
end
|
78
|
+
|
79
|
+
break if $exit
|
80
|
+
end
|
81
|
+
|
82
|
+
ensure
|
83
|
+
Delayed::Job.clear_locks!(name)
|
84
|
+
end
|
85
|
+
|
86
|
+
# Do num jobs and return stats on success/failure.
|
87
|
+
# Exit early if interrupted.
|
88
|
+
def work_off(num = 100)
|
89
|
+
success, failure = 0, 0
|
90
|
+
|
91
|
+
num.times do
|
92
|
+
case reserve_and_run_one_job
|
93
|
+
when true
|
94
|
+
success += 1
|
95
|
+
when false
|
96
|
+
failure += 1
|
97
|
+
else
|
98
|
+
break # leave if no work could be done
|
99
|
+
end
|
100
|
+
break if $exit # leave if we're exiting
|
101
|
+
end
|
102
|
+
|
103
|
+
return [success, failure]
|
104
|
+
end
|
105
|
+
|
106
|
+
def run(job)
|
107
|
+
runtime = Benchmark.realtime do
|
108
|
+
Timeout.timeout(self.class.max_run_time.to_i) { job.invoke_job }
|
109
|
+
job.destroy
|
110
|
+
end
|
111
|
+
# TODO: warn if runtime > max_run_time ?
|
112
|
+
say "* [JOB] #{name} completed after %.4f" % runtime
|
113
|
+
return true # did work
|
114
|
+
rescue Exception => e
|
115
|
+
handle_failed_job(job, e)
|
116
|
+
return false # work failed
|
117
|
+
end
|
118
|
+
|
119
|
+
# Reschedule the job in the future (when a job fails).
|
120
|
+
# Uses an exponential scale depending on the number of failed attempts.
|
121
|
+
def reschedule(job, time = nil)
|
122
|
+
if (job.attempts += 1) < self.class.max_attempts
|
123
|
+
time ||= Job.db_time_now + (job.attempts ** 4) + 5
|
124
|
+
job.run_at = time
|
125
|
+
job.unlock
|
126
|
+
job.save!
|
127
|
+
else
|
128
|
+
say "* [JOB] PERMANENTLY removing #{job.name} because of #{job.attempts} consecutive failures.", Logger::INFO
|
129
|
+
self.class.destroy_failed_jobs ? job.destroy : job.update_attribute(:failed_at, Delayed::Job.db_time_now)
|
130
|
+
end
|
131
|
+
end
|
132
|
+
|
133
|
+
def say(text, level = Logger::INFO)
|
134
|
+
puts text unless @quiet
|
135
|
+
logger.add level, "#{Time.now.strftime('%FT%T%z')}: #{text}" if logger
|
136
|
+
end
|
137
|
+
|
138
|
+
protected
|
139
|
+
|
140
|
+
def handle_failed_job(job, error)
|
141
|
+
job.last_error = error.message + "\n" + error.backtrace.join("\n")
|
142
|
+
say "* [JOB] #{name} failed with #{error.class.name}: #{error.message} - #{job.attempts} failed attempts", Logger::ERROR
|
143
|
+
reschedule(job)
|
144
|
+
end
|
145
|
+
|
146
|
+
# Run the next job we can get an exclusive lock on.
|
147
|
+
# If no jobs are left we return nil
|
148
|
+
def reserve_and_run_one_job
|
149
|
+
|
150
|
+
# We get up to 5 jobs from the db. In case we cannot get exclusive access to a job we try the next.
|
151
|
+
# this leads to a more even distribution of jobs across the worker processes
|
152
|
+
job = Delayed::Job.find_available(name, 5, self.class.max_run_time).detect do |job|
|
153
|
+
if job.lock_exclusively!(self.class.max_run_time, name)
|
154
|
+
say "* [Worker(#{name})] acquired lock on #{job.name}"
|
155
|
+
true
|
156
|
+
else
|
157
|
+
say "* [Worker(#{name})] failed to acquire exclusive lock for #{job.name}", Logger::WARN
|
158
|
+
false
|
159
|
+
end
|
160
|
+
end
|
161
|
+
|
162
|
+
run(job) if job
|
163
|
+
end
|
164
|
+
end
|
165
|
+
end
|