delayed_job_on_steroids 1.7.1
Sign up to get free protection for your applications and to get access to all the features.
- data/.gitignore +2 -0
- data/MIT-LICENSE +20 -0
- data/README.textile +121 -0
- data/Rakefile +45 -0
- data/VERSION +1 -0
- data/delayed_job_on_steroids.gemspec +65 -0
- data/generators/delayed_job_migration/delayed_job_migration_generator.rb +15 -0
- data/generators/delayed_job_migration/templates/migration.rb +22 -0
- data/init.rb +1 -0
- data/lib/delayed/job.rb +272 -0
- data/lib/delayed/message_sending.rb +17 -0
- data/lib/delayed/performable_method.rb +55 -0
- data/lib/delayed/worker.rb +54 -0
- data/lib/delayed_job.rb +13 -0
- data/spec/database.rb +43 -0
- data/spec/delayed_method_spec.rb +128 -0
- data/spec/job_spec.rb +345 -0
- data/spec/story_spec.rb +17 -0
- data/tasks/jobs.rake +1 -0
- data/tasks/tasks.rb +15 -0
- metadata +98 -0
data/.gitignore
ADDED
data/MIT-LICENSE
ADDED
@@ -0,0 +1,20 @@
|
|
1
|
+
Copyright (c) 2005 Tobias Luetke
|
2
|
+
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
4
|
+
a copy of this software and associated documentation files (the
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
9
|
+
the following conditions:
|
10
|
+
|
11
|
+
The above copyright notice and this permission notice shall be
|
12
|
+
included in all copies or substantial portions of the Software.
|
13
|
+
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOa AND
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SaALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.textile
ADDED
@@ -0,0 +1,121 @@
|
|
1
|
+
h1. Delayed::Job
|
2
|
+
|
3
|
+
Delayed_job (or DJ) encapsulates the common pattern of asynchronously executing longer tasks in the background.
|
4
|
+
|
5
|
+
It is a direct extraction from Shopify where the job table is responsible for a multitude of core tasks. Amongst those tasks are:
|
6
|
+
|
7
|
+
* sending massive newsletters
|
8
|
+
* image resizing
|
9
|
+
* http downloads
|
10
|
+
* updating smart collections
|
11
|
+
* updating solr, our search server, after product changes
|
12
|
+
* batch imports
|
13
|
+
* spam checks
|
14
|
+
|
15
|
+
h2. Setup
|
16
|
+
|
17
|
+
The library evolves around a delayed_jobs table which can be created by using:
|
18
|
+
<pre><code>
|
19
|
+
script/generate delayed_job_migration
|
20
|
+
</code></pre>
|
21
|
+
|
22
|
+
The created table looks as follows:
|
23
|
+
|
24
|
+
<pre><code>
|
25
|
+
create_table :delayed_jobs, :force => true do |table|
|
26
|
+
table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
|
27
|
+
table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
|
28
|
+
table.text :handler # YAML-encoded string of the object that will do work
|
29
|
+
table.string :last_error # reason for last failure (See Note below)
|
30
|
+
table.datetime :run_at # When to run. Could be Time.now for immediately, or sometime in the future.
|
31
|
+
table.datetime :locked_at # Set when a client is working on this object
|
32
|
+
table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
|
33
|
+
table.string :locked_by # Who is working on this object (if locked)
|
34
|
+
table.timestamps
|
35
|
+
end
|
36
|
+
</code></pre>
|
37
|
+
|
38
|
+
On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries.
|
39
|
+
|
40
|
+
The default @MAX_ATTEMPTS@ is @25@. After this, the job either deleted (default), or left in the database with "failed_at" set.
|
41
|
+
With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours.
|
42
|
+
|
43
|
+
The default @MAX_RUN_TIME@ is @4.hours@. If your job takes longer than that, another computer could pick it up. It's up to you to
|
44
|
+
make sure your job doesn't exceed this time. You should set this to the longest time you think the job could take.
|
45
|
+
|
46
|
+
By default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set
|
47
|
+
@Delayed::Job.destroy_failed_jobs = false@. The failed jobs will be marked with non-null failed_at.
|
48
|
+
|
49
|
+
Here is an example of changing job parameters in Rails:
|
50
|
+
|
51
|
+
<pre><code>
|
52
|
+
# config/initializers/delayed_job_config.rb
|
53
|
+
Delayed::Job.destroy_failed_jobs = false
|
54
|
+
silence_warnings do
|
55
|
+
Delayed::Job.const_set("MAX_ATTEMPTS", 3)
|
56
|
+
Delayed::Job.const_set("MAX_RUN_TIME", 5.minutes)
|
57
|
+
end
|
58
|
+
</code></pre>
|
59
|
+
|
60
|
+
Note: If your error messages are long, consider changing last_error field to a :text instead of a :string (255 character limit).
|
61
|
+
|
62
|
+
|
63
|
+
h2. Usage
|
64
|
+
|
65
|
+
Jobs are simple ruby objects with a method called perform. Any object which responds to perform can be stuffed into the jobs table.
|
66
|
+
Job objects are serialized to yaml so that they can later be resurrected by the job runner.
|
67
|
+
|
68
|
+
<pre><code>
|
69
|
+
class NewsletterJob < Struct.new(:text, :emails)
|
70
|
+
def perform
|
71
|
+
emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
|
72
|
+
end
|
73
|
+
end
|
74
|
+
|
75
|
+
Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.find(:all).collect(&:email))
|
76
|
+
</code></pre>
|
77
|
+
|
78
|
+
There is also a second way to get jobs in the queue: send_later.
|
79
|
+
|
80
|
+
<pre><code>
|
81
|
+
BatchImporter.new(Shop.find(1)).send_later(:import_massive_csv, massive_csv)
|
82
|
+
</code></pre>
|
83
|
+
|
84
|
+
This will simply create a @Delayed::PerformableMethod@ job in the jobs table which serializes all the parameters you pass to it. There are some special smarts for active record objects
|
85
|
+
which are stored as their text representation and loaded from the database fresh when the job is actually run later.
|
86
|
+
|
87
|
+
|
88
|
+
h2. Running the jobs
|
89
|
+
|
90
|
+
You can invoke @rake jobs:work@ which will start working off jobs. You can cancel the rake task with @CTRL-C@.
|
91
|
+
|
92
|
+
You can also run by writing a simple @script/job_runner@, and invoking it externally:
|
93
|
+
|
94
|
+
<pre><code>
|
95
|
+
#!/usr/bin/env ruby
|
96
|
+
require File.dirname(__FILE__) + '/../config/environment'
|
97
|
+
|
98
|
+
Delayed::Worker.new.start
|
99
|
+
</code></pre>
|
100
|
+
|
101
|
+
Workers can be running on any computer, as long as they have access to the database and their clock is in sync. You can even
|
102
|
+
run multiple workers on per computer, but you must give each one a unique name. (TODO: put in an example)
|
103
|
+
Keep in mind that each worker will check the database at least every 5 seconds.
|
104
|
+
|
105
|
+
Note: The rake task will exit if the database has any network connectivity problems.
|
106
|
+
|
107
|
+
h3. Cleaning up
|
108
|
+
|
109
|
+
You can invoke @rake jobs:clear@ to delete all jobs in the queue.
|
110
|
+
|
111
|
+
h3. Changes
|
112
|
+
|
113
|
+
* 1.7.0: Added failed_at column which can optionally be set after a certain amount of failed job attempts. By default failed job attempts are destroyed after about a month.
|
114
|
+
|
115
|
+
* 1.6.0: Renamed locked_until to locked_at. We now store when we start a given job instead of how long it will be locked by the worker. This allows us to get a reading on how long a job took to execute.
|
116
|
+
|
117
|
+
* 1.5.0: Job runners can now be run in parallel. Two new database columns are needed: locked_until and locked_by. This allows us to use pessimistic locking instead of relying on row level locks. This enables us to run as many worker processes as we need to speed up queue processing.
|
118
|
+
|
119
|
+
* 1.2.0: Added #send_later to Object for simpler job creation
|
120
|
+
|
121
|
+
* 1.0.0: Initial release
|
data/Rakefile
ADDED
@@ -0,0 +1,45 @@
|
|
1
|
+
require 'rubygems'
|
2
|
+
require 'rake'
|
3
|
+
|
4
|
+
begin
|
5
|
+
require 'jeweler'
|
6
|
+
Jeweler::Tasks.new do |gem|
|
7
|
+
gem.name = "delayed_job_on_steroids"
|
8
|
+
gem.summary = "Database-backed asynchronous priority queue system, extended and improved"
|
9
|
+
gem.description = "Delated_job (or DJ) encapsulates the common pattern of asynchronously executing longer tasks in the background."
|
10
|
+
gem.email = "aleksey.palazhchenko@gmail.com"
|
11
|
+
gem.homepage = "http://github.com/AlekSi/delayed_job_on_steroids"
|
12
|
+
gem.authors = ["Tobias Lütke", "Aleksey Palazhchenko"]
|
13
|
+
gem.add_development_dependency "rspec", ">= 1.2.9"
|
14
|
+
# gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
|
15
|
+
end
|
16
|
+
Jeweler::GemcutterTasks.new
|
17
|
+
rescue LoadError
|
18
|
+
puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
|
19
|
+
end
|
20
|
+
|
21
|
+
require 'spec/rake/spectask'
|
22
|
+
Spec::Rake::SpecTask.new(:spec) do |spec|
|
23
|
+
spec.libs << 'lib' << 'spec'
|
24
|
+
spec.spec_files = FileList['spec/**/*_spec.rb']
|
25
|
+
end
|
26
|
+
|
27
|
+
Spec::Rake::SpecTask.new(:rcov) do |spec|
|
28
|
+
spec.libs << 'lib' << 'spec'
|
29
|
+
spec.pattern = 'spec/**/*_spec.rb'
|
30
|
+
spec.rcov = true
|
31
|
+
end
|
32
|
+
|
33
|
+
task :spec => :check_dependencies
|
34
|
+
|
35
|
+
task :default => :spec
|
36
|
+
|
37
|
+
require 'rake/rdoctask'
|
38
|
+
Rake::RDocTask.new do |rdoc|
|
39
|
+
version = File.exist?('VERSION') ? File.read('VERSION') : ""
|
40
|
+
|
41
|
+
rdoc.rdoc_dir = 'rdoc'
|
42
|
+
rdoc.title = "delayed_job_on_steroids #{version}"
|
43
|
+
rdoc.rdoc_files.include('README*')
|
44
|
+
rdoc.rdoc_files.include('lib/**/*.rb')
|
45
|
+
end
|
data/VERSION
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
1.7.1
|
@@ -0,0 +1,65 @@
|
|
1
|
+
# Generated by jeweler
|
2
|
+
# DO NOT EDIT THIS FILE DIRECTLY
|
3
|
+
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
|
4
|
+
# -*- encoding: utf-8 -*-
|
5
|
+
|
6
|
+
Gem::Specification.new do |s|
|
7
|
+
s.name = %q{delayed_job_on_steroids}
|
8
|
+
s.version = "1.7.1"
|
9
|
+
|
10
|
+
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
|
11
|
+
s.authors = ["Tobias L\303\274tke", "Aleksey Palazhchenko"]
|
12
|
+
s.date = %q{2010-03-15}
|
13
|
+
s.description = %q{Delated_job (or DJ) encapsulates the common pattern of asynchronously executing longer tasks in the background.}
|
14
|
+
s.email = %q{aleksey.palazhchenko@gmail.com}
|
15
|
+
s.extra_rdoc_files = [
|
16
|
+
"README.textile"
|
17
|
+
]
|
18
|
+
s.files = [
|
19
|
+
".gitignore",
|
20
|
+
"MIT-LICENSE",
|
21
|
+
"README.textile",
|
22
|
+
"Rakefile",
|
23
|
+
"VERSION",
|
24
|
+
"delayed_job_on_steroids.gemspec",
|
25
|
+
"generators/delayed_job_migration/delayed_job_migration_generator.rb",
|
26
|
+
"generators/delayed_job_migration/templates/migration.rb",
|
27
|
+
"init.rb",
|
28
|
+
"lib/delayed/job.rb",
|
29
|
+
"lib/delayed/message_sending.rb",
|
30
|
+
"lib/delayed/performable_method.rb",
|
31
|
+
"lib/delayed/worker.rb",
|
32
|
+
"lib/delayed_job.rb",
|
33
|
+
"spec/database.rb",
|
34
|
+
"spec/delayed_method_spec.rb",
|
35
|
+
"spec/job_spec.rb",
|
36
|
+
"spec/story_spec.rb",
|
37
|
+
"tasks/jobs.rake",
|
38
|
+
"tasks/tasks.rb"
|
39
|
+
]
|
40
|
+
s.homepage = %q{http://github.com/AlekSi/delayed_job_on_steroids}
|
41
|
+
s.rdoc_options = ["--charset=UTF-8"]
|
42
|
+
s.require_paths = ["lib"]
|
43
|
+
s.rubygems_version = %q{1.3.6}
|
44
|
+
s.summary = %q{Database-backed asynchronous priority queue system, extended and improved}
|
45
|
+
s.test_files = [
|
46
|
+
"spec/delayed_method_spec.rb",
|
47
|
+
"spec/job_spec.rb",
|
48
|
+
"spec/story_spec.rb",
|
49
|
+
"spec/database.rb"
|
50
|
+
]
|
51
|
+
|
52
|
+
if s.respond_to? :specification_version then
|
53
|
+
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
|
54
|
+
s.specification_version = 3
|
55
|
+
|
56
|
+
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
|
57
|
+
s.add_development_dependency(%q<rspec>, [">= 1.2.9"])
|
58
|
+
else
|
59
|
+
s.add_dependency(%q<rspec>, [">= 1.2.9"])
|
60
|
+
end
|
61
|
+
else
|
62
|
+
s.add_dependency(%q<rspec>, [">= 1.2.9"])
|
63
|
+
end
|
64
|
+
end
|
65
|
+
|
@@ -0,0 +1,15 @@
|
|
1
|
+
class DelayedJobMigrationGenerator < Rails::Generator::Base
|
2
|
+
def manifest
|
3
|
+
record do |m|
|
4
|
+
options = {
|
5
|
+
:migration_file_name => 'create_delayed_jobs'
|
6
|
+
}
|
7
|
+
|
8
|
+
m.migration_template 'migration.rb', 'db/migrate', options
|
9
|
+
end
|
10
|
+
end
|
11
|
+
|
12
|
+
def banner
|
13
|
+
"Usage: #{$0} #{spec.name}"
|
14
|
+
end
|
15
|
+
end
|
@@ -0,0 +1,22 @@
|
|
1
|
+
class CreateDelayedJobs < ActiveRecord::Migration
|
2
|
+
def self.up
|
3
|
+
create_table :delayed_jobs, :force => true do |t|
|
4
|
+
t.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
|
5
|
+
t.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
|
6
|
+
t.text :handler # YAML-encoded string of the object that will do work
|
7
|
+
t.string :last_error # reason for last failure (See Note below)
|
8
|
+
t.datetime :run_at # When to run. Could be Time.now for immediately, or sometime in the future.
|
9
|
+
t.datetime :locked_at # Set when a client is working on this object
|
10
|
+
t.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
|
11
|
+
t.string :locked_by # Who is working on this object (if locked)
|
12
|
+
|
13
|
+
t.timestamps
|
14
|
+
end
|
15
|
+
|
16
|
+
add_index :delayed_jobs, :locked_by
|
17
|
+
end
|
18
|
+
|
19
|
+
def self.down
|
20
|
+
drop_table :delayed_jobs
|
21
|
+
end
|
22
|
+
end
|
data/init.rb
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
require File.dirname(__FILE__) + '/lib/delayed_job'
|
data/lib/delayed/job.rb
ADDED
@@ -0,0 +1,272 @@
|
|
1
|
+
module Delayed
|
2
|
+
|
3
|
+
class DeserializationError < StandardError
|
4
|
+
end
|
5
|
+
|
6
|
+
# A job object that is persisted to the database.
|
7
|
+
# Contains the work object as a YAML field.
|
8
|
+
class Job < ActiveRecord::Base
|
9
|
+
MAX_ATTEMPTS = 25
|
10
|
+
MAX_RUN_TIME = 4.hours
|
11
|
+
set_table_name :delayed_jobs
|
12
|
+
|
13
|
+
# By default failed jobs are destroyed after too many attempts.
|
14
|
+
# If you want to keep them around (perhaps to inspect the reason
|
15
|
+
# for the failure), set this to false.
|
16
|
+
cattr_accessor :destroy_failed_jobs
|
17
|
+
self.destroy_failed_jobs = true
|
18
|
+
|
19
|
+
# Every worker has a unique name which by default is the pid of the process.
|
20
|
+
# There are some advantages to overriding this with something which survives worker retarts:
|
21
|
+
# Workers can safely resume working on tasks which are locked by themselves. The worker will assume that it crashed before.
|
22
|
+
cattr_accessor :worker_name
|
23
|
+
self.worker_name = "host:#{Socket.gethostname} pid:#{Process.pid}" rescue "pid:#{Process.pid}"
|
24
|
+
|
25
|
+
NextTaskSQL = '(run_at <= ? AND (locked_at IS NULL OR locked_at < ?) OR (locked_by = ?)) AND failed_at IS NULL'
|
26
|
+
NextTaskOrder = 'priority DESC, run_at ASC'
|
27
|
+
|
28
|
+
ParseObjectFromYaml = /\!ruby\/\w+\:([^\s]+)/
|
29
|
+
|
30
|
+
cattr_accessor :min_priority, :max_priority
|
31
|
+
self.min_priority = nil
|
32
|
+
self.max_priority = nil
|
33
|
+
|
34
|
+
# When a worker is exiting, make sure we don't have any locked jobs.
|
35
|
+
def self.clear_locks!
|
36
|
+
update_all("locked_by = null, locked_at = null", ["locked_by = ?", worker_name])
|
37
|
+
end
|
38
|
+
|
39
|
+
def failed?
|
40
|
+
failed_at
|
41
|
+
end
|
42
|
+
alias_method :failed, :failed?
|
43
|
+
|
44
|
+
def payload_object
|
45
|
+
@payload_object ||= deserialize(self['handler'])
|
46
|
+
end
|
47
|
+
|
48
|
+
def name
|
49
|
+
@name ||= begin
|
50
|
+
payload = payload_object
|
51
|
+
if payload.respond_to?(:display_name)
|
52
|
+
payload.display_name
|
53
|
+
else
|
54
|
+
payload.class.name
|
55
|
+
end
|
56
|
+
end
|
57
|
+
end
|
58
|
+
|
59
|
+
def payload_object=(object)
|
60
|
+
self['handler'] = object.to_yaml
|
61
|
+
end
|
62
|
+
|
63
|
+
# Reschedule the job in the future (when a job fails).
|
64
|
+
# Uses an exponential scale depending on the number of failed attempts.
|
65
|
+
def reschedule(message, backtrace = [], time = nil)
|
66
|
+
if self.attempts < MAX_ATTEMPTS
|
67
|
+
time ||= Job.db_time_now + (attempts ** 4) + 5
|
68
|
+
|
69
|
+
self.attempts += 1
|
70
|
+
self.run_at = time
|
71
|
+
self.last_error = message + "\n" + backtrace.join("\n")
|
72
|
+
self.unlock
|
73
|
+
save!
|
74
|
+
else
|
75
|
+
logger.info "* [JOB] PERMANENTLY removing #{self.name} because of #{attempts} consequetive failures."
|
76
|
+
destroy_failed_jobs ? destroy : update_attribute(:failed_at, Delayed::Job.db_time_now)
|
77
|
+
end
|
78
|
+
end
|
79
|
+
|
80
|
+
|
81
|
+
# Try to run one job. Returns true/false (work done/work failed) or nil if job can't be locked.
|
82
|
+
def run_with_lock(max_run_time, worker_name)
|
83
|
+
logger.info "* [JOB] aquiring lock on #{name}"
|
84
|
+
unless lock_exclusively!(max_run_time, worker_name)
|
85
|
+
# We did not get the lock, some other worker process must have
|
86
|
+
logger.warn "* [JOB] failed to aquire exclusive lock for #{name}"
|
87
|
+
return nil # no work done
|
88
|
+
end
|
89
|
+
|
90
|
+
begin
|
91
|
+
runtime = Benchmark.realtime do
|
92
|
+
invoke_job # TODO: raise error if takes longer than max_run_time
|
93
|
+
destroy
|
94
|
+
end
|
95
|
+
# TODO: warn if runtime > max_run_time ?
|
96
|
+
logger.info "* [JOB] #{name} completed after %.4f" % runtime
|
97
|
+
return true # did work
|
98
|
+
rescue Exception => e
|
99
|
+
reschedule e.message, e.backtrace
|
100
|
+
log_exception(e)
|
101
|
+
return false # work failed
|
102
|
+
end
|
103
|
+
end
|
104
|
+
|
105
|
+
# Add a job to the queue
|
106
|
+
def self.enqueue(*args, &block)
|
107
|
+
object = block_given? ? EvaledJob.new(&block) : args.shift
|
108
|
+
|
109
|
+
unless object.respond_to?(:perform) || block_given?
|
110
|
+
raise ArgumentError, 'Cannot enqueue items which do not respond to perform'
|
111
|
+
end
|
112
|
+
|
113
|
+
priority = args.first || 0
|
114
|
+
run_at = args[1]
|
115
|
+
|
116
|
+
Job.create(:payload_object => object, :priority => priority.to_i, :run_at => run_at)
|
117
|
+
end
|
118
|
+
|
119
|
+
# Find a few candidate jobs to run (in case some immediately get locked by others).
|
120
|
+
# Return in random order prevent everyone trying to do same head job at once.
|
121
|
+
def self.find_available(limit = 5, max_run_time = MAX_RUN_TIME)
|
122
|
+
|
123
|
+
time_now = db_time_now
|
124
|
+
|
125
|
+
sql = NextTaskSQL.dup
|
126
|
+
|
127
|
+
conditions = [time_now, time_now - max_run_time, worker_name]
|
128
|
+
|
129
|
+
if self.min_priority
|
130
|
+
sql << ' AND (priority >= ?)'
|
131
|
+
conditions << min_priority
|
132
|
+
end
|
133
|
+
|
134
|
+
if self.max_priority
|
135
|
+
sql << ' AND (priority <= ?)'
|
136
|
+
conditions << max_priority
|
137
|
+
end
|
138
|
+
|
139
|
+
conditions.unshift(sql)
|
140
|
+
|
141
|
+
records = ActiveRecord::Base.silence do
|
142
|
+
find(:all, :conditions => conditions, :order => NextTaskOrder, :limit => limit)
|
143
|
+
end
|
144
|
+
|
145
|
+
records.sort_by { rand() }
|
146
|
+
end
|
147
|
+
|
148
|
+
# Run the next job we can get an exclusive lock on.
|
149
|
+
# If no jobs are left we return nil
|
150
|
+
def self.reserve_and_run_one_job(max_run_time = MAX_RUN_TIME)
|
151
|
+
|
152
|
+
# We get up to 5 jobs from the db. In case we cannot get exclusive access to a job we try the next.
|
153
|
+
# this leads to a more even distribution of jobs across the worker processes
|
154
|
+
find_available(5, max_run_time).each do |job|
|
155
|
+
t = job.run_with_lock(max_run_time, worker_name)
|
156
|
+
return t unless t == nil # return if we did work (good or bad)
|
157
|
+
end
|
158
|
+
|
159
|
+
nil # we didn't do any work, all 5 were not lockable
|
160
|
+
end
|
161
|
+
|
162
|
+
# Lock this job for this worker.
|
163
|
+
# Returns true if we have the lock, false otherwise.
|
164
|
+
def lock_exclusively!(max_run_time, worker = worker_name)
|
165
|
+
now = self.class.db_time_now
|
166
|
+
affected_rows = if locked_by != worker
|
167
|
+
# We don't own this job so we will update the locked_by name and the locked_at
|
168
|
+
self.class.update_all(["locked_at = ?, locked_by = ?", now, worker], ["id = ? and (locked_at is null or locked_at < ?)", id, (now - max_run_time.to_i)])
|
169
|
+
else
|
170
|
+
# We already own this job, this may happen if the job queue crashes.
|
171
|
+
# Simply resume and update the locked_at
|
172
|
+
self.class.update_all(["locked_at = ?", now], ["id = ? and locked_by = ?", id, worker])
|
173
|
+
end
|
174
|
+
if affected_rows == 1
|
175
|
+
self.locked_at = now
|
176
|
+
self.locked_by = worker
|
177
|
+
return true
|
178
|
+
else
|
179
|
+
return false
|
180
|
+
end
|
181
|
+
end
|
182
|
+
|
183
|
+
# Unlock this job (note: not saved to DB)
|
184
|
+
def unlock
|
185
|
+
self.locked_at = nil
|
186
|
+
self.locked_by = nil
|
187
|
+
end
|
188
|
+
|
189
|
+
# This is a good hook if you need to report job processing errors in additional or different ways
|
190
|
+
def log_exception(error)
|
191
|
+
logger.error "* [JOB] #{name} failed with #{error.class.name}: #{error.message} - #{attempts} failed attempts"
|
192
|
+
logger.error(error)
|
193
|
+
end
|
194
|
+
|
195
|
+
# Do num jobs and return stats on success/failure.
|
196
|
+
# Exit early if interrupted.
|
197
|
+
def self.work_off(num = 100)
|
198
|
+
success, failure = 0, 0
|
199
|
+
|
200
|
+
num.times do
|
201
|
+
case self.reserve_and_run_one_job
|
202
|
+
when true
|
203
|
+
success += 1
|
204
|
+
when false
|
205
|
+
failure += 1
|
206
|
+
else
|
207
|
+
break # leave if no work could be done
|
208
|
+
end
|
209
|
+
break if $exit # leave if we're exiting
|
210
|
+
end
|
211
|
+
|
212
|
+
return [success, failure]
|
213
|
+
end
|
214
|
+
|
215
|
+
# Moved into its own method so that new_relic can trace it.
|
216
|
+
def invoke_job
|
217
|
+
payload_object.perform
|
218
|
+
end
|
219
|
+
|
220
|
+
private
|
221
|
+
|
222
|
+
def deserialize(source)
|
223
|
+
handler = YAML.load(source) rescue nil
|
224
|
+
|
225
|
+
unless handler.respond_to?(:perform)
|
226
|
+
if handler.nil? && source =~ ParseObjectFromYaml
|
227
|
+
handler_class = $1
|
228
|
+
end
|
229
|
+
attempt_to_load(handler_class || handler.class)
|
230
|
+
handler = YAML.load(source)
|
231
|
+
end
|
232
|
+
|
233
|
+
return handler if handler.respond_to?(:perform)
|
234
|
+
|
235
|
+
raise DeserializationError,
|
236
|
+
'Job failed to load: Unknown handler. Try to manually require the appropiate file.'
|
237
|
+
rescue TypeError, LoadError, NameError => e
|
238
|
+
raise DeserializationError,
|
239
|
+
"Job failed to load: #{e.message}. Try to manually require the required file."
|
240
|
+
end
|
241
|
+
|
242
|
+
# Constantize the object so that ActiveSupport can attempt
|
243
|
+
# its auto loading magic. Will raise LoadError if not successful.
|
244
|
+
def attempt_to_load(klass)
|
245
|
+
klass.constantize
|
246
|
+
end
|
247
|
+
|
248
|
+
# Get the current time (GMT or local depending on DB)
|
249
|
+
# Note: This does not ping the DB to get the time, so all your clients
|
250
|
+
# must have syncronized clocks.
|
251
|
+
def self.db_time_now
|
252
|
+
(ActiveRecord::Base.default_timezone == :utc) ? Time.now.utc : Time.zone.now
|
253
|
+
end
|
254
|
+
|
255
|
+
protected
|
256
|
+
|
257
|
+
def before_save
|
258
|
+
self.run_at ||= self.class.db_time_now
|
259
|
+
end
|
260
|
+
|
261
|
+
end
|
262
|
+
|
263
|
+
class EvaledJob
|
264
|
+
def initialize
|
265
|
+
@job = yield
|
266
|
+
end
|
267
|
+
|
268
|
+
def perform
|
269
|
+
eval(@job)
|
270
|
+
end
|
271
|
+
end
|
272
|
+
end
|
@@ -0,0 +1,17 @@
|
|
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
|
+
module ClassMethods
|
8
|
+
def handle_asynchronously(method)
|
9
|
+
without_name = "#{method}_without_send_later"
|
10
|
+
define_method("#{method}_with_send_later") do |*args|
|
11
|
+
send_later(without_name, *args)
|
12
|
+
end
|
13
|
+
alias_method_chain method, :send_later
|
14
|
+
end
|
15
|
+
end
|
16
|
+
end
|
17
|
+
end
|
@@ -0,0 +1,55 @@
|
|
1
|
+
module Delayed
|
2
|
+
class PerformableMethod < Struct.new(:object, :method, :args)
|
3
|
+
CLASS_STRING_FORMAT = /^CLASS\:([A-Z][\w\:]+)$/
|
4
|
+
AR_STRING_FORMAT = /^AR\:([A-Z][\w\:]+)\:(\d+)$/
|
5
|
+
|
6
|
+
def initialize(object, method, args)
|
7
|
+
raise NoMethodError, "undefined method `#{method}' for #{self.inspect}" unless object.respond_to?(method)
|
8
|
+
|
9
|
+
self.object = dump(object)
|
10
|
+
self.args = args.map { |a| dump(a) }
|
11
|
+
self.method = method.to_sym
|
12
|
+
end
|
13
|
+
|
14
|
+
def display_name
|
15
|
+
case self.object
|
16
|
+
when CLASS_STRING_FORMAT then "#{$1}.#{method}"
|
17
|
+
when AR_STRING_FORMAT then "#{$1}##{method}"
|
18
|
+
else "Unknown##{method}"
|
19
|
+
end
|
20
|
+
end
|
21
|
+
|
22
|
+
def perform
|
23
|
+
load(object).send(method, *args.map{|a| load(a)})
|
24
|
+
rescue ActiveRecord::RecordNotFound
|
25
|
+
# We cannot do anything about objects which were deleted in the meantime
|
26
|
+
true
|
27
|
+
end
|
28
|
+
|
29
|
+
private
|
30
|
+
|
31
|
+
def load(arg)
|
32
|
+
case arg
|
33
|
+
when CLASS_STRING_FORMAT then $1.constantize
|
34
|
+
when AR_STRING_FORMAT then $1.constantize.find($2)
|
35
|
+
else arg
|
36
|
+
end
|
37
|
+
end
|
38
|
+
|
39
|
+
def dump(arg)
|
40
|
+
case arg
|
41
|
+
when Class then class_to_string(arg)
|
42
|
+
when ActiveRecord::Base then ar_to_string(arg)
|
43
|
+
else arg
|
44
|
+
end
|
45
|
+
end
|
46
|
+
|
47
|
+
def ar_to_string(obj)
|
48
|
+
"AR:#{obj.class}:#{obj.id}"
|
49
|
+
end
|
50
|
+
|
51
|
+
def class_to_string(obj)
|
52
|
+
"CLASS:#{obj.name}"
|
53
|
+
end
|
54
|
+
end
|
55
|
+
end
|