topprospect-delayed_job 2.0.5
Sign up to get free protection for your applications and to get access to all the features.
- data/MIT-LICENSE +20 -0
- data/README.textile +210 -0
- data/contrib/delayed_job.monitrc +14 -0
- data/contrib/delayed_job_multiple.monitrc +23 -0
- data/lib/delayed/backend/active_record.rb +97 -0
- data/lib/delayed/backend/active_record.rb.orig +105 -0
- data/lib/delayed/backend/base.rb +85 -0
- data/lib/delayed/backend/couch_rest.rb +109 -0
- data/lib/delayed/backend/data_mapper.rb +121 -0
- data/lib/delayed/backend/mongo_mapper.rb +106 -0
- data/lib/delayed/command.rb +107 -0
- data/lib/delayed/message_sending.rb +45 -0
- data/lib/delayed/performable_method.rb +27 -0
- data/lib/delayed/railtie.rb +14 -0
- data/lib/delayed/recipes.rb +31 -0
- data/lib/delayed/tasks.rb +20 -0
- data/lib/delayed/tasks.rb.orig +26 -0
- data/lib/delayed/worker.rb +213 -0
- data/lib/delayed/worker.rb.orig +202 -0
- data/lib/delayed/yaml_ext.rb +40 -0
- data/lib/delayed_job.rb +15 -0
- data/lib/generators/delayed_job/delayed_job_generator.rb +34 -0
- data/lib/generators/delayed_job/templates/migration.rb +21 -0
- data/lib/generators/delayed_job/templates/script +5 -0
- data/recipes/delayed_job.rb +1 -0
- data/spec/autoloaded/clazz.rb +7 -0
- data/spec/autoloaded/struct.rb +7 -0
- data/spec/backend/active_record_job_spec.rb +54 -0
- data/spec/backend/couch_rest_job_spec.rb +15 -0
- data/spec/backend/data_mapper_job_spec.rb +16 -0
- data/spec/backend/mongo_mapper_job_spec.rb +94 -0
- data/spec/backend/shared_backend_spec.rb +280 -0
- data/spec/message_sending_spec.rb +51 -0
- data/spec/performable_method_spec.rb +48 -0
- data/spec/sample_jobs.rb +25 -0
- data/spec/setup/active_record.rb +54 -0
- data/spec/setup/couch_rest.rb +7 -0
- data/spec/setup/data_mapper.rb +8 -0
- data/spec/setup/mongo_mapper.rb +17 -0
- data/spec/spec_helper.rb +31 -0
- data/spec/worker_spec.rb +214 -0
- metadata +300 -0
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,210 @@
|
|
1
|
+
h1. Delayed::Job
|
2
|
+
|
3
|
+
Delated_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. Installation
|
16
|
+
|
17
|
+
To install as a gem, add the following to @config/environment.rb@:
|
18
|
+
|
19
|
+
<pre>
|
20
|
+
config.gem 'delayed_job'
|
21
|
+
</pre>
|
22
|
+
|
23
|
+
Rake tasks are not automatically loaded from gems, so you'll need to add the following to your Rakefile:
|
24
|
+
|
25
|
+
<pre>
|
26
|
+
begin
|
27
|
+
require 'delayed/tasks'
|
28
|
+
rescue LoadError
|
29
|
+
STDERR.puts "Run `rake gems:install` to install delayed_job"
|
30
|
+
end
|
31
|
+
</pre>
|
32
|
+
|
33
|
+
To install as a plugin:
|
34
|
+
|
35
|
+
<pre>
|
36
|
+
script/plugin install git://github.com/collectiveidea/delayed_job.git
|
37
|
+
</pre>
|
38
|
+
|
39
|
+
After delayed_job is installed, you will need to setup the backend.
|
40
|
+
|
41
|
+
h2. Backends
|
42
|
+
|
43
|
+
delayed_job supports multiple backends for storing the job queue. There are currently implementations for Active Record, MongoMapper, and DataMapper.
|
44
|
+
|
45
|
+
h3. Active Record
|
46
|
+
|
47
|
+
The default is Active Record, which requires a jobs table.
|
48
|
+
|
49
|
+
<pre>
|
50
|
+
$ script/generate delayed_job
|
51
|
+
$ rake db:migrate
|
52
|
+
</pre>
|
53
|
+
|
54
|
+
h3. MongoMapper
|
55
|
+
|
56
|
+
You must use @MongoMapper.setup@ in the initializer:
|
57
|
+
|
58
|
+
<pre>
|
59
|
+
config = YAML::load(File.read(Rails.root.join('config/mongo.yml')))
|
60
|
+
MongoMapper.setup(config, Rails.env)
|
61
|
+
|
62
|
+
Delayed::Worker.backend = :mongo_mapper
|
63
|
+
</pre>
|
64
|
+
|
65
|
+
h3. DataMapper
|
66
|
+
|
67
|
+
<pre>
|
68
|
+
# config/initializers/delayed_job.rb
|
69
|
+
Delayed::Worker.backend = :data_mapper
|
70
|
+
Delayed::Worker.backend.auto_upgrade!
|
71
|
+
</pre>
|
72
|
+
|
73
|
+
h2. Queuing Jobs
|
74
|
+
|
75
|
+
Call @.delay.method(params)@ on any object and it will be processed in the background.
|
76
|
+
|
77
|
+
<pre>
|
78
|
+
# without delayed_job
|
79
|
+
Notifier.deliver_signup(@user)
|
80
|
+
|
81
|
+
# with delayed_job
|
82
|
+
Notifier.delay.deliver_signup @user
|
83
|
+
</pre>
|
84
|
+
|
85
|
+
If a method should always be run in the background, you can call @#handle_asynchronously@ after the method declaration:
|
86
|
+
|
87
|
+
<pre>
|
88
|
+
class Device
|
89
|
+
def deliver
|
90
|
+
# long running method
|
91
|
+
end
|
92
|
+
handle_asynchronously :deliver
|
93
|
+
end
|
94
|
+
|
95
|
+
device = Device.new
|
96
|
+
device.deliver
|
97
|
+
</pre>
|
98
|
+
|
99
|
+
h2. Running Jobs
|
100
|
+
|
101
|
+
@script/delayed_job@ can be used to manage a background process which will start working off jobs. Make sure you've run `script/generate delayed_job`.
|
102
|
+
|
103
|
+
<pre>
|
104
|
+
$ RAILS_ENV=production script/delayed_job start
|
105
|
+
$ RAILS_ENV=production script/delayed_job stop
|
106
|
+
|
107
|
+
# Runs two workers in separate processes.
|
108
|
+
$ RAILS_ENV=production script/delayed_job -n 2 start
|
109
|
+
$ RAILS_ENV=production script/delayed_job stop
|
110
|
+
</pre>
|
111
|
+
|
112
|
+
Workers can be running on any computer, as long as they have access to the database and their clock is in sync. Keep in mind that each worker will check the database at least every 5 seconds.
|
113
|
+
|
114
|
+
You can also invoke @rake jobs:work@ which will start working off jobs. You can cancel the rake task with @CTRL-C@.
|
115
|
+
|
116
|
+
h2. Custom Jobs
|
117
|
+
|
118
|
+
Jobs are simple ruby objects with a method called perform. Any object which responds to perform can be stuffed into the jobs table. Job objects are serialized to yaml so that they can later be resurrected by the job runner.
|
119
|
+
|
120
|
+
<pre>
|
121
|
+
class NewsletterJob < Struct.new(:text, :emails)
|
122
|
+
def perform
|
123
|
+
emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
|
124
|
+
end
|
125
|
+
end
|
126
|
+
|
127
|
+
Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.find(:all).collect(&:email))
|
128
|
+
</pre>
|
129
|
+
|
130
|
+
You can also add an optional on_permanent_failure method which will run if the job has failed too many times to be retried:
|
131
|
+
|
132
|
+
<pre>
|
133
|
+
class ParanoidNewsletterJob < NewsletterJob
|
134
|
+
def perform
|
135
|
+
emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
|
136
|
+
end
|
137
|
+
|
138
|
+
def on_permanent_failure
|
139
|
+
page_sysadmin_in_the_middle_of_the_night
|
140
|
+
end
|
141
|
+
end
|
142
|
+
</pre>
|
143
|
+
|
144
|
+
h2. Gory Details
|
145
|
+
|
146
|
+
The library evolves around a delayed_jobs table which looks as follows:
|
147
|
+
|
148
|
+
<pre>
|
149
|
+
create_table :delayed_jobs, :force => true do |table|
|
150
|
+
table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
|
151
|
+
table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
|
152
|
+
table.text :handler # YAML-encoded string of the object that will do work
|
153
|
+
table.text :last_error # reason for last failure (See Note below)
|
154
|
+
table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future.
|
155
|
+
table.datetime :locked_at # Set when a client is working on this object
|
156
|
+
table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
|
157
|
+
table.string :locked_by # Who is working on this object (if locked)
|
158
|
+
table.timestamps
|
159
|
+
end
|
160
|
+
</pre>
|
161
|
+
|
162
|
+
On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries.
|
163
|
+
|
164
|
+
The default Worker.max_attempts is 25. After this, the job either deleted (default), or left in the database with "failed_at" set.
|
165
|
+
With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours.
|
166
|
+
|
167
|
+
The default Worker.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
|
168
|
+
make sure your job doesn't exceed this time. You should set this to the longest time you think the job could take.
|
169
|
+
|
170
|
+
By default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set
|
171
|
+
Delayed::Worker.destroy_failed_jobs = false. The failed jobs will be marked with non-null failed_at.
|
172
|
+
|
173
|
+
Here is an example of changing job parameters in Rails:
|
174
|
+
|
175
|
+
<pre>
|
176
|
+
# config/initializers/delayed_job_config.rb
|
177
|
+
Delayed::Worker.destroy_failed_jobs = false
|
178
|
+
Delayed::Worker.sleep_delay = 60
|
179
|
+
Delayed::Worker.max_attempts = 3
|
180
|
+
Delayed::Worker.max_run_time = 5.minutes
|
181
|
+
</pre>
|
182
|
+
|
183
|
+
h3. Cleaning up
|
184
|
+
|
185
|
+
You can invoke @rake jobs:clear@ to delete all jobs in the queue.
|
186
|
+
|
187
|
+
h2. Mailing List
|
188
|
+
|
189
|
+
Join us on the mailing list at http://groups.google.com/group/delayed_job
|
190
|
+
|
191
|
+
h2. How to contribute
|
192
|
+
|
193
|
+
If you find what looks like a bug:
|
194
|
+
|
195
|
+
# Check the GitHub issue tracker to see if anyone else has had the same issue.
|
196
|
+
http://github.com/collectiveidea/delayed_job/issues/
|
197
|
+
# If you don't see anything, create an issue with information on how to reproduce it.
|
198
|
+
|
199
|
+
If you want to contribute an enhancement or a fix:
|
200
|
+
|
201
|
+
# Fork the project on github.
|
202
|
+
http://github.com/collectiveidea/delayed_job/
|
203
|
+
# Make your changes with tests.
|
204
|
+
# Commit the changes without making changes to the Rakefile, VERSION, or any other files that aren't related to your enhancement or fix
|
205
|
+
# Send a pull request.
|
206
|
+
|
207
|
+
h3. Changelog
|
208
|
+
|
209
|
+
See http://wiki.github.com/collectiveidea/delayed_job/changelog for a list of changes.
|
210
|
+
|
@@ -0,0 +1,14 @@
|
|
1
|
+
# an example Monit configuration file for delayed_job
|
2
|
+
# See: http://stackoverflow.com/questions/1226302/how-to-monitor-delayedjob-with-monit/1285611
|
3
|
+
#
|
4
|
+
# To use:
|
5
|
+
# 1. copy to /var/www/apps/{app_name}/shared/delayed_job.monitrc
|
6
|
+
# 2. replace {app_name} as appropriate
|
7
|
+
# 3. add this to your /etc/monit/monitrc
|
8
|
+
#
|
9
|
+
# include /var/www/apps/{app_name}/shared/delayed_job.monitrc
|
10
|
+
|
11
|
+
check process delayed_job
|
12
|
+
with pidfile /var/www/apps/{app_name}/shared/pids/delayed_job.pid
|
13
|
+
start program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job start"
|
14
|
+
stop program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job stop"
|
@@ -0,0 +1,23 @@
|
|
1
|
+
# an example Monit configuration file for delayed_job running multiple processes
|
2
|
+
#
|
3
|
+
# To use:
|
4
|
+
# 1. copy to /var/www/apps/{app_name}/shared/delayed_job.monitrc
|
5
|
+
# 2. replace {app_name} as appropriate
|
6
|
+
# 3. add this to your /etc/monit/monitrc
|
7
|
+
#
|
8
|
+
# include /var/www/apps/{app_name}/shared/delayed_job.monitrc
|
9
|
+
|
10
|
+
check process delayed_job_0
|
11
|
+
with pidfile /var/www/apps/{app_name}/shared/pids/delayed_job.0.pid
|
12
|
+
start program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job start -i 0"
|
13
|
+
stop program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job stop -i 0"
|
14
|
+
|
15
|
+
check process delayed_job_1
|
16
|
+
with pidfile /var/www/apps/{app_name}/shared/pids/delayed_job.1.pid
|
17
|
+
start program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job start -i 1"
|
18
|
+
stop program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job stop -i 1"
|
19
|
+
|
20
|
+
check process delayed_job_2
|
21
|
+
with pidfile /var/www/apps/{app_name}/shared/pids/delayed_job.2.pid
|
22
|
+
start program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job start -i 2"
|
23
|
+
stop program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job stop -i 2"
|
@@ -0,0 +1,97 @@
|
|
1
|
+
require 'active_record'
|
2
|
+
|
3
|
+
class ActiveRecord::Base
|
4
|
+
yaml_as "tag:ruby.yaml.org,2002:ActiveRecord"
|
5
|
+
|
6
|
+
def self.yaml_new(klass, tag, val)
|
7
|
+
klass.find(val['attributes']['id'])
|
8
|
+
rescue ActiveRecord::RecordNotFound
|
9
|
+
nil
|
10
|
+
end
|
11
|
+
|
12
|
+
def to_yaml_properties
|
13
|
+
['@attributes']
|
14
|
+
end
|
15
|
+
end
|
16
|
+
|
17
|
+
module Delayed
|
18
|
+
module Backend
|
19
|
+
module ActiveRecord
|
20
|
+
# A job object that is persisted to the database.
|
21
|
+
# Contains the work object as a YAML field.
|
22
|
+
class Job < ::ActiveRecord::Base
|
23
|
+
include Delayed::Backend::Base
|
24
|
+
set_table_name :delayed_jobs
|
25
|
+
|
26
|
+
before_save :set_default_run_at
|
27
|
+
|
28
|
+
if ::ActiveRecord::VERSION::MAJOR >= 3
|
29
|
+
scope :ready_to_run, lambda {|worker_name, max_run_time|
|
30
|
+
where(['(run_at <= ? AND (locked_at IS NULL OR locked_at < ?) OR locked_by = ?) AND failed_at IS NULL', db_time_now, db_time_now - max_run_time, worker_name])
|
31
|
+
}
|
32
|
+
scope :by_priority, order('priority ASC, run_at ASC')
|
33
|
+
else
|
34
|
+
named_scope :ready_to_run, lambda {|worker_name, max_run_time|
|
35
|
+
{:conditions => ['queue = ? AND (run_at <= ? AND (locked_at IS NULL OR locked_at < ?) OR locked_by = ?) AND failed_at IS NULL', Worker.queue, db_time_now, db_time_now - max_run_time, worker_name]}
|
36
|
+
}
|
37
|
+
named_scope :by_priority, :order => 'priority ASC, run_at ASC'
|
38
|
+
end
|
39
|
+
|
40
|
+
def self.after_fork
|
41
|
+
::ActiveRecord::Base.connection.reconnect!
|
42
|
+
end
|
43
|
+
|
44
|
+
# When a worker is exiting, make sure we don't have any locked jobs.
|
45
|
+
def self.clear_locks!(worker_name)
|
46
|
+
update_all("locked_by = null, locked_at = null", ["locked_by = ?", worker_name])
|
47
|
+
end
|
48
|
+
|
49
|
+
# Find a few candidate jobs to run (in case some immediately get locked by others).
|
50
|
+
def self.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time)
|
51
|
+
scope = self.ready_to_run(worker_name, max_run_time)
|
52
|
+
scope = scope.scoped(:conditions => ['priority >= ?', Worker.min_priority]) if Worker.min_priority
|
53
|
+
scope = scope.scoped(:conditions => ['priority <= ?', Worker.max_priority]) if Worker.max_priority
|
54
|
+
|
55
|
+
::ActiveRecord::Base.silence do
|
56
|
+
scope.by_priority.all(:limit => limit)
|
57
|
+
end
|
58
|
+
end
|
59
|
+
|
60
|
+
# Lock this job for this worker.
|
61
|
+
# Returns true if we have the lock, false otherwise.
|
62
|
+
def lock_exclusively!(max_run_time, worker)
|
63
|
+
now = self.class.db_time_now
|
64
|
+
affected_rows = if locked_by != worker
|
65
|
+
# We don't own this job so we will update the locked_by name and the locked_at
|
66
|
+
self.class.update_all(["locked_at = ?, locked_by = ?", now, worker], ["id = ? and (locked_at is null or locked_at < ?) and (run_at <= ?)", id, (now - max_run_time.to_i), now])
|
67
|
+
else
|
68
|
+
# We already own this job, this may happen if the job queue crashes.
|
69
|
+
# Simply resume and update the locked_at
|
70
|
+
self.class.update_all(["locked_at = ?", now], ["id = ? and locked_by = ?", id, worker])
|
71
|
+
end
|
72
|
+
if affected_rows == 1
|
73
|
+
self.locked_at = now
|
74
|
+
self.locked_by = worker
|
75
|
+
return true
|
76
|
+
else
|
77
|
+
return false
|
78
|
+
end
|
79
|
+
end
|
80
|
+
|
81
|
+
# Get the current time (GMT or local depending on DB)
|
82
|
+
# Note: This does not ping the DB to get the time, so all your clients
|
83
|
+
# must have syncronized clocks.
|
84
|
+
def self.db_time_now
|
85
|
+
if Time.zone
|
86
|
+
Time.zone.now
|
87
|
+
elsif ::ActiveRecord::Base.default_timezone == :utc
|
88
|
+
Time.now.utc
|
89
|
+
else
|
90
|
+
Time.now
|
91
|
+
end
|
92
|
+
end
|
93
|
+
|
94
|
+
end
|
95
|
+
end
|
96
|
+
end
|
97
|
+
end
|
@@ -0,0 +1,105 @@
|
|
1
|
+
require 'active_record'
|
2
|
+
|
3
|
+
class ActiveRecord::Base
|
4
|
+
yaml_as "tag:ruby.yaml.org,2002:ActiveRecord"
|
5
|
+
|
6
|
+
def self.yaml_new(klass, tag, val)
|
7
|
+
klass.find(val['attributes']['id'])
|
8
|
+
rescue ActiveRecord::RecordNotFound
|
9
|
+
nil
|
10
|
+
end
|
11
|
+
|
12
|
+
def to_yaml_properties
|
13
|
+
['@attributes']
|
14
|
+
end
|
15
|
+
end
|
16
|
+
|
17
|
+
module Delayed
|
18
|
+
module Backend
|
19
|
+
module ActiveRecord
|
20
|
+
# A job object that is persisted to the database.
|
21
|
+
# Contains the work object as a YAML field.
|
22
|
+
class Job < ::ActiveRecord::Base
|
23
|
+
include Delayed::Backend::Base
|
24
|
+
set_table_name :delayed_jobs
|
25
|
+
|
26
|
+
before_save :set_default_run_at
|
27
|
+
|
28
|
+
<<<<<<< HEAD
|
29
|
+
if ::ActiveRecord::VERSION::MAJOR >= 3
|
30
|
+
scope :ready_to_run, lambda {|worker_name, max_run_time|
|
31
|
+
where(['(run_at <= ? AND (locked_at IS NULL OR locked_at < ?) OR locked_by = ?) AND failed_at IS NULL', db_time_now, db_time_now - max_run_time, worker_name])
|
32
|
+
}
|
33
|
+
scope :by_priority, order('priority ASC, run_at ASC')
|
34
|
+
else
|
35
|
+
named_scope :ready_to_run, lambda {|worker_name, max_run_time|
|
36
|
+
{:conditions => ['queue = ? AND (run_at <= ? AND (locked_at IS NULL OR locked_at < ?) OR locked_by = ?) AND failed_at IS NULL', Worker.queue, db_time_now, db_time_now - max_run_time, worker_name]}
|
37
|
+
}
|
38
|
+
named_scope :by_priority, :order => 'priority ASC, run_at ASC'
|
39
|
+
end
|
40
|
+
|
41
|
+
=======
|
42
|
+
named_scope :ready_to_run, lambda {|worker_name, max_run_time|
|
43
|
+
{:conditions => ['queue = ? AND (run_at <= ? AND (locked_at IS NULL OR locked_at < ?) OR locked_by = ?) AND failed_at IS NULL', Worker.queue, db_time_now, db_time_now - max_run_time, worker_name]}
|
44
|
+
}
|
45
|
+
named_scope :by_priority, :order => 'priority ASC, run_at ASC'
|
46
|
+
|
47
|
+
>>>>>>> 75b6e0c... added queues from the original topprospect patch, added tests for queues
|
48
|
+
def self.after_fork
|
49
|
+
::ActiveRecord::Base.connection.reconnect!
|
50
|
+
end
|
51
|
+
|
52
|
+
# When a worker is exiting, make sure we don't have any locked jobs.
|
53
|
+
def self.clear_locks!(worker_name)
|
54
|
+
update_all("locked_by = null, locked_at = null", ["locked_by = ?", worker_name])
|
55
|
+
end
|
56
|
+
|
57
|
+
# Find a few candidate jobs to run (in case some immediately get locked by others).
|
58
|
+
def self.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time)
|
59
|
+
scope = self.ready_to_run(worker_name, max_run_time)
|
60
|
+
scope = scope.scoped(:conditions => ['priority >= ?', Worker.min_priority]) if Worker.min_priority
|
61
|
+
scope = scope.scoped(:conditions => ['priority <= ?', Worker.max_priority]) if Worker.max_priority
|
62
|
+
|
63
|
+
::ActiveRecord::Base.silence do
|
64
|
+
scope.by_priority.all(:limit => limit)
|
65
|
+
end
|
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)
|
71
|
+
now = self.class.db_time_now
|
72
|
+
affected_rows = if locked_by != worker
|
73
|
+
# We don't own this job so we will update the locked_by name and the locked_at
|
74
|
+
self.class.update_all(["locked_at = ?, locked_by = ?", now, worker], ["id = ? and (locked_at is null or locked_at < ?) and (run_at <= ?)", id, (now - max_run_time.to_i), now])
|
75
|
+
else
|
76
|
+
# We already own this job, this may happen if the job queue crashes.
|
77
|
+
# Simply resume and update the locked_at
|
78
|
+
self.class.update_all(["locked_at = ?", now], ["id = ? and locked_by = ?", id, worker])
|
79
|
+
end
|
80
|
+
if affected_rows == 1
|
81
|
+
self.locked_at = now
|
82
|
+
self.locked_by = worker
|
83
|
+
return true
|
84
|
+
else
|
85
|
+
return false
|
86
|
+
end
|
87
|
+
end
|
88
|
+
|
89
|
+
# Get the current time (GMT or local depending on DB)
|
90
|
+
# Note: This does not ping the DB to get the time, so all your clients
|
91
|
+
# must have syncronized clocks.
|
92
|
+
def self.db_time_now
|
93
|
+
if Time.zone
|
94
|
+
Time.zone.now
|
95
|
+
elsif ::ActiveRecord::Base.default_timezone == :utc
|
96
|
+
Time.now.utc
|
97
|
+
else
|
98
|
+
Time.now
|
99
|
+
end
|
100
|
+
end
|
101
|
+
|
102
|
+
end
|
103
|
+
end
|
104
|
+
end
|
105
|
+
end
|
@@ -0,0 +1,85 @@
|
|
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 || Delayed::Worker.default_priority
|
20
|
+
run_at = args[1]
|
21
|
+
# we just added queue to the positional argument list and to self.create,
|
22
|
+
# TODO will it break for other backends where :queue is not defined yet?
|
23
|
+
queue = args[2] || Delayed::Worker.queue
|
24
|
+
self.create(:payload_object => object, :priority => priority.to_i, :run_at => run_at, :queue => queue)
|
25
|
+
end
|
26
|
+
|
27
|
+
# Hook method that is called before a new worker is forked
|
28
|
+
def before_fork
|
29
|
+
end
|
30
|
+
|
31
|
+
# Hook method that is called after a new worker is forked
|
32
|
+
def after_fork
|
33
|
+
end
|
34
|
+
|
35
|
+
def work_off(num = 100)
|
36
|
+
warn "[DEPRECATION] `Delayed::Job.work_off` is deprecated. Use `Delayed::Worker.new.work_off instead."
|
37
|
+
Delayed::Worker.new.work_off(num)
|
38
|
+
end
|
39
|
+
end
|
40
|
+
|
41
|
+
ParseObjectFromYaml = /\!ruby\/\w+\:([^\s]+)/
|
42
|
+
|
43
|
+
def failed?
|
44
|
+
failed_at
|
45
|
+
end
|
46
|
+
alias_method :failed, :failed?
|
47
|
+
|
48
|
+
def name
|
49
|
+
@name ||= begin
|
50
|
+
payload = payload_object
|
51
|
+
payload.respond_to?(:display_name) ? payload.display_name : payload.class.name
|
52
|
+
end
|
53
|
+
end
|
54
|
+
|
55
|
+
def payload_object=(object)
|
56
|
+
self.handler = object.to_yaml
|
57
|
+
end
|
58
|
+
|
59
|
+
def payload_object
|
60
|
+
@payload_object ||= YAML.load(self.handler)
|
61
|
+
rescue TypeError, LoadError, NameError => e
|
62
|
+
raise DeserializationError,
|
63
|
+
"Job failed to load: #{e.message}. Try to manually require the required file. Handler: #{handler.inspect}"
|
64
|
+
end
|
65
|
+
|
66
|
+
# Moved into its own method so that new_relic can trace it.
|
67
|
+
def invoke_job
|
68
|
+
payload_object.perform
|
69
|
+
end
|
70
|
+
|
71
|
+
# Unlock this job (note: not saved to DB)
|
72
|
+
def unlock
|
73
|
+
self.locked_at = nil
|
74
|
+
self.locked_by = nil
|
75
|
+
end
|
76
|
+
|
77
|
+
protected
|
78
|
+
|
79
|
+
def set_default_run_at
|
80
|
+
self.run_at ||= self.class.db_time_now
|
81
|
+
end
|
82
|
+
|
83
|
+
end
|
84
|
+
end
|
85
|
+
end
|
@@ -0,0 +1,109 @@
|
|
1
|
+
require 'couchrest'
|
2
|
+
|
3
|
+
#extent couchrest to handle delayed_job serialization.
|
4
|
+
class CouchRest::ExtendedDocument
|
5
|
+
yaml_as "tag:ruby.yaml.org,2002:CouchRest"
|
6
|
+
|
7
|
+
def reload
|
8
|
+
job = self.class.get self['_id']
|
9
|
+
job.each {|k,v| self[k] = v}
|
10
|
+
end
|
11
|
+
def self.find(id)
|
12
|
+
get id
|
13
|
+
end
|
14
|
+
def self.yaml_new(klass, tag, val)
|
15
|
+
klass.get(val['_id'])
|
16
|
+
end
|
17
|
+
def ==(other)
|
18
|
+
if other.is_a? ::CouchRest::ExtendedDocument
|
19
|
+
self['_id'] == other['_id']
|
20
|
+
else
|
21
|
+
super
|
22
|
+
end
|
23
|
+
end
|
24
|
+
end
|
25
|
+
|
26
|
+
#couchrest adapter
|
27
|
+
module Delayed
|
28
|
+
module Backend
|
29
|
+
module CouchRest
|
30
|
+
class Job < ::CouchRest::ExtendedDocument
|
31
|
+
include Delayed::Backend::Base
|
32
|
+
use_database ::CouchRest::Server.new.database('delayed_job')
|
33
|
+
|
34
|
+
property :handler
|
35
|
+
property :last_error
|
36
|
+
property :locked_by
|
37
|
+
property :priority, :default => 0
|
38
|
+
property :attempts, :default => 0
|
39
|
+
property :run_at, :cast_as => 'Time'
|
40
|
+
property :locked_at, :cast_as => 'Time'
|
41
|
+
property :failed_at, :cast_as => 'Time'
|
42
|
+
timestamps!
|
43
|
+
|
44
|
+
set_callback :save, :before, :set_default_run_at
|
45
|
+
|
46
|
+
view_by(:failed_at, :locked_by, :run_at,
|
47
|
+
:map => "function(doc){" +
|
48
|
+
" if(doc['couchrest-type'] == 'Delayed::Backend::CouchRest::Job') {" +
|
49
|
+
" emit([doc.failed_at || null, doc.locked_by || null, doc.run_at || null], null);}" +
|
50
|
+
" }")
|
51
|
+
view_by(:failed_at, :locked_at, :run_at,
|
52
|
+
:map => "function(doc){" +
|
53
|
+
" if(doc['couchrest-type'] == 'Delayed::Backend::CouchRest::Job') {" +
|
54
|
+
" emit([doc.failed_at || null, doc.locked_at || null, doc.run_at || null], null);}" +
|
55
|
+
" }")
|
56
|
+
|
57
|
+
def self.db_time_now; Time.now; end
|
58
|
+
def self.find_available(worker_name, limit = 5, max_run_time = ::Delayed::Worker.max_run_time)
|
59
|
+
ready = ready_jobs
|
60
|
+
mine = my_jobs worker_name
|
61
|
+
expire = expired_jobs max_run_time
|
62
|
+
jobs = (ready + mine + expire)[0..limit-1].sort_by { |j| j.priority }
|
63
|
+
jobs = jobs.find_all { |j| j.priority >= Worker.min_priority } if Worker.min_priority
|
64
|
+
jobs = jobs.find_all { |j| j.priority <= Worker.max_priority } if Worker.max_priority
|
65
|
+
jobs
|
66
|
+
end
|
67
|
+
def self.clear_locks!(worker_name)
|
68
|
+
jobs = my_jobs worker_name
|
69
|
+
jobs.each { |j| j.locked_by, j.locked_at = nil, nil; }
|
70
|
+
database.bulk_save jobs
|
71
|
+
end
|
72
|
+
def self.delete_all
|
73
|
+
database.bulk_save all.each { |doc| doc['_deleted'] = true }
|
74
|
+
end
|
75
|
+
|
76
|
+
def lock_exclusively!(max_run_time, worker = worker_name)
|
77
|
+
return false if locked_by_other?(worker) and not expired?(max_run_time)
|
78
|
+
case
|
79
|
+
when locked_by_me?(worker)
|
80
|
+
self.locked_at = self.class.db_time_now
|
81
|
+
when (unlocked? or (locked_by_other?(worker) and expired?(max_run_time)))
|
82
|
+
self.locked_at, self.locked_by = self.class.db_time_now, worker
|
83
|
+
end
|
84
|
+
save
|
85
|
+
rescue RestClient::Conflict
|
86
|
+
false
|
87
|
+
end
|
88
|
+
|
89
|
+
private
|
90
|
+
def self.ready_jobs
|
91
|
+
options = {:startkey => [nil, nil], :endkey => [nil, nil, db_time_now]}
|
92
|
+
by_failed_at_and_locked_by_and_run_at options
|
93
|
+
end
|
94
|
+
def self.my_jobs(worker_name)
|
95
|
+
options = {:startkey => [nil, worker_name], :endkey => [nil, worker_name, {}]}
|
96
|
+
by_failed_at_and_locked_by_and_run_at options
|
97
|
+
end
|
98
|
+
def self.expired_jobs(max_run_time)
|
99
|
+
options = {:startkey => [nil,'0'], :endkey => [nil, db_time_now - max_run_time, db_time_now]}
|
100
|
+
by_failed_at_and_locked_at_and_run_at options
|
101
|
+
end
|
102
|
+
def unlocked?; locked_by.nil?; end
|
103
|
+
def expired?(time); locked_at < self.class.db_time_now - time; end
|
104
|
+
def locked_by_me?(worker); not locked_by.nil? and locked_by == worker; end
|
105
|
+
def locked_by_other?(worker); not locked_by.nil? and locked_by != worker; end
|
106
|
+
end
|
107
|
+
end
|
108
|
+
end
|
109
|
+
end
|