andrewtimberlake-delayed_job 1.8.4.1
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 +121 -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 +281 -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 +44 -0
- data/spec/delayed_method_spec.rb +128 -0
- data/spec/job_spec.rb +381 -0
- data/spec/story_spec.rb +17 -0
- data/tasks/jobs.rake +1 -0
- data/tasks/tasks.rb +15 -0
- metadata +75 -0
data/.gitignore
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
*.gem
|
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
|
@@ -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,281 @@
|
|
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, :runner_name
|
31
|
+
self.min_priority = nil
|
32
|
+
self.max_priority = nil
|
33
|
+
self.runner_name = nil
|
34
|
+
|
35
|
+
# When a worker is exiting, make sure we don't have any locked jobs.
|
36
|
+
def self.clear_locks!
|
37
|
+
update_all("locked_by = null, locked_at = null", ["locked_by = ?", worker_name])
|
38
|
+
end
|
39
|
+
|
40
|
+
def failed?
|
41
|
+
failed_at
|
42
|
+
end
|
43
|
+
alias_method :failed, :failed?
|
44
|
+
|
45
|
+
def payload_object
|
46
|
+
@payload_object ||= deserialize(self['handler'])
|
47
|
+
end
|
48
|
+
|
49
|
+
def name
|
50
|
+
@name ||= begin
|
51
|
+
payload = payload_object
|
52
|
+
if payload.respond_to?(:display_name)
|
53
|
+
payload.display_name
|
54
|
+
else
|
55
|
+
payload.class.name
|
56
|
+
end
|
57
|
+
end
|
58
|
+
end
|
59
|
+
|
60
|
+
def payload_object=(object)
|
61
|
+
self['handler'] = object.to_yaml
|
62
|
+
end
|
63
|
+
|
64
|
+
# Reschedule the job in the future (when a job fails).
|
65
|
+
# Uses an exponential scale depending on the number of failed attempts.
|
66
|
+
def reschedule(message, backtrace = [], time = nil)
|
67
|
+
if self.attempts < MAX_ATTEMPTS
|
68
|
+
time ||= Job.db_time_now + (attempts ** 4) + 5
|
69
|
+
|
70
|
+
self.attempts += 1
|
71
|
+
self.run_at = time
|
72
|
+
self.last_error = message + "\n" + backtrace.join("\n")
|
73
|
+
self.unlock
|
74
|
+
save!
|
75
|
+
else
|
76
|
+
logger.info "* [JOB] PERMANENTLY removing #{self.name} because of #{attempts} consequetive failures."
|
77
|
+
destroy_failed_jobs ? destroy : update_attribute(:failed_at, Delayed::Job.db_time_now)
|
78
|
+
end
|
79
|
+
end
|
80
|
+
|
81
|
+
|
82
|
+
# Try to run one job. Returns true/false (work done/work failed) or nil if job can't be locked.
|
83
|
+
def run_with_lock(max_run_time, worker_name)
|
84
|
+
logger.info "* [JOB] aquiring lock on #{name}"
|
85
|
+
unless lock_exclusively!(max_run_time, worker_name)
|
86
|
+
# We did not get the lock, some other worker process must have
|
87
|
+
logger.warn "* [JOB] failed to aquire exclusive lock for #{name}"
|
88
|
+
return nil # no work done
|
89
|
+
end
|
90
|
+
|
91
|
+
begin
|
92
|
+
runtime = Benchmark.realtime do
|
93
|
+
invoke_job # TODO: raise error if takes longer than max_run_time
|
94
|
+
destroy
|
95
|
+
end
|
96
|
+
# TODO: warn if runtime > max_run_time ?
|
97
|
+
logger.info "* [JOB] #{name} completed after %.4f" % runtime
|
98
|
+
return true # did work
|
99
|
+
rescue Exception => e
|
100
|
+
reschedule e.message, e.backtrace
|
101
|
+
log_exception(e)
|
102
|
+
return false # work failed
|
103
|
+
end
|
104
|
+
end
|
105
|
+
|
106
|
+
# Add a job to the queue
|
107
|
+
def self.enqueue(*args, &block)
|
108
|
+
object = block_given? ? EvaledJob.new(&block) : args.shift
|
109
|
+
|
110
|
+
unless object.respond_to?(:perform) || block_given?
|
111
|
+
raise ArgumentError, 'Cannot enqueue items which do not respond to perform'
|
112
|
+
end
|
113
|
+
|
114
|
+
options = args.first || {}
|
115
|
+
options[:priority] ||= 0
|
116
|
+
options[:payload_object] = object
|
117
|
+
|
118
|
+
Job.create options
|
119
|
+
end
|
120
|
+
|
121
|
+
# Find a few candidate jobs to run (in case some immediately get locked by others).
|
122
|
+
# Return in random order prevent everyone trying to do same head job at once.
|
123
|
+
def self.find_available(limit = 5, max_run_time = MAX_RUN_TIME)
|
124
|
+
|
125
|
+
time_now = db_time_now
|
126
|
+
|
127
|
+
sql = NextTaskSQL.dup
|
128
|
+
|
129
|
+
conditions = [time_now, time_now - max_run_time, worker_name]
|
130
|
+
|
131
|
+
if self.runner_name
|
132
|
+
sql << ' AND (runner = ?)'
|
133
|
+
conditions << runner_name
|
134
|
+
else
|
135
|
+
sql << ' AND (runner is null)'
|
136
|
+
end
|
137
|
+
|
138
|
+
if self.min_priority
|
139
|
+
sql << ' AND (priority >= ?)'
|
140
|
+
conditions << min_priority
|
141
|
+
end
|
142
|
+
|
143
|
+
if self.max_priority
|
144
|
+
sql << ' AND (priority <= ?)'
|
145
|
+
conditions << max_priority
|
146
|
+
end
|
147
|
+
|
148
|
+
conditions.unshift(sql)
|
149
|
+
|
150
|
+
records = ActiveRecord::Base.silence do
|
151
|
+
find(:all, :conditions => conditions, :order => NextTaskOrder, :limit => limit)
|
152
|
+
end
|
153
|
+
|
154
|
+
records.sort_by { rand() }
|
155
|
+
end
|
156
|
+
|
157
|
+
# Run the next job we can get an exclusive lock on.
|
158
|
+
# If no jobs are left we return nil
|
159
|
+
def self.reserve_and_run_one_job(max_run_time = MAX_RUN_TIME)
|
160
|
+
|
161
|
+
# We get up to 5 jobs from the db. In case we cannot get exclusive access to a job we try the next.
|
162
|
+
# this leads to a more even distribution of jobs across the worker processes
|
163
|
+
find_available(5, max_run_time).each do |job|
|
164
|
+
t = job.run_with_lock(max_run_time, worker_name)
|
165
|
+
return t unless t == nil # return if we did work (good or bad)
|
166
|
+
end
|
167
|
+
|
168
|
+
nil # we didn't do any work, all 5 were not lockable
|
169
|
+
end
|
170
|
+
|
171
|
+
# Lock this job for this worker.
|
172
|
+
# Returns true if we have the lock, false otherwise.
|
173
|
+
def lock_exclusively!(max_run_time, worker = worker_name)
|
174
|
+
now = self.class.db_time_now
|
175
|
+
affected_rows = if locked_by != worker
|
176
|
+
# We don't own this job so we will update the locked_by name and the locked_at
|
177
|
+
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)])
|
178
|
+
else
|
179
|
+
# We already own this job, this may happen if the job queue crashes.
|
180
|
+
# Simply resume and update the locked_at
|
181
|
+
self.class.update_all(["locked_at = ?", now], ["id = ? and locked_by = ?", id, worker])
|
182
|
+
end
|
183
|
+
if affected_rows == 1
|
184
|
+
self.locked_at = now
|
185
|
+
self.locked_by = worker
|
186
|
+
return true
|
187
|
+
else
|
188
|
+
return false
|
189
|
+
end
|
190
|
+
end
|
191
|
+
|
192
|
+
# Unlock this job (note: not saved to DB)
|
193
|
+
def unlock
|
194
|
+
self.locked_at = nil
|
195
|
+
self.locked_by = nil
|
196
|
+
end
|
197
|
+
|
198
|
+
# This is a good hook if you need to report job processing errors in additional or different ways
|
199
|
+
def log_exception(error)
|
200
|
+
logger.error "* [JOB] #{name} failed with #{error.class.name}: #{error.message} - #{attempts} failed attempts"
|
201
|
+
logger.error(error)
|
202
|
+
end
|
203
|
+
|
204
|
+
# Do num jobs and return stats on success/failure.
|
205
|
+
# Exit early if interrupted.
|
206
|
+
def self.work_off(num = 100)
|
207
|
+
success, failure = 0, 0
|
208
|
+
|
209
|
+
num.times do
|
210
|
+
case self.reserve_and_run_one_job
|
211
|
+
when true
|
212
|
+
success += 1
|
213
|
+
when false
|
214
|
+
failure += 1
|
215
|
+
else
|
216
|
+
break # leave if no work could be done
|
217
|
+
end
|
218
|
+
break if $exit # leave if we're exiting
|
219
|
+
end
|
220
|
+
|
221
|
+
return [success, failure]
|
222
|
+
end
|
223
|
+
|
224
|
+
# Moved into its own method so that new_relic can trace it.
|
225
|
+
def invoke_job
|
226
|
+
payload_object.perform
|
227
|
+
end
|
228
|
+
|
229
|
+
private
|
230
|
+
|
231
|
+
def deserialize(source)
|
232
|
+
handler = YAML.load(source) rescue nil
|
233
|
+
|
234
|
+
unless handler.respond_to?(:perform)
|
235
|
+
if handler.nil? && source =~ ParseObjectFromYaml
|
236
|
+
handler_class = $1
|
237
|
+
end
|
238
|
+
attempt_to_load(handler_class || handler.class)
|
239
|
+
handler = YAML.load(source)
|
240
|
+
end
|
241
|
+
|
242
|
+
return handler if handler.respond_to?(:perform)
|
243
|
+
|
244
|
+
raise DeserializationError,
|
245
|
+
'Job failed to load: Unknown handler. Try to manually require the appropiate file.'
|
246
|
+
rescue TypeError, LoadError, NameError => e
|
247
|
+
raise DeserializationError,
|
248
|
+
"Job failed to load: #{e.message}. Try to manually require the required file."
|
249
|
+
end
|
250
|
+
|
251
|
+
# Constantize the object so that ActiveSupport can attempt
|
252
|
+
# its auto loading magic. Will raise LoadError if not successful.
|
253
|
+
def attempt_to_load(klass)
|
254
|
+
klass.constantize
|
255
|
+
end
|
256
|
+
|
257
|
+
# Get the current time (GMT or local depending on DB)
|
258
|
+
# Note: This does not ping the DB to get the time, so all your clients
|
259
|
+
# must have syncronized clocks.
|
260
|
+
def self.db_time_now
|
261
|
+
(ActiveRecord::Base.default_timezone == :utc) ? Time.now.utc : Time.zone.now
|
262
|
+
end
|
263
|
+
|
264
|
+
protected
|
265
|
+
|
266
|
+
def before_save
|
267
|
+
self.run_at ||= self.class.db_time_now
|
268
|
+
end
|
269
|
+
|
270
|
+
end
|
271
|
+
|
272
|
+
class EvaledJob
|
273
|
+
def initialize
|
274
|
+
@job = yield
|
275
|
+
end
|
276
|
+
|
277
|
+
def perform
|
278
|
+
eval(@job)
|
279
|
+
end
|
280
|
+
end
|
281
|
+
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
|
@@ -0,0 +1,54 @@
|
|
1
|
+
module Delayed
|
2
|
+
class Worker
|
3
|
+
SLEEP = 5
|
4
|
+
|
5
|
+
cattr_accessor :logger
|
6
|
+
self.logger = if defined?(Merb::Logger)
|
7
|
+
Merb.logger
|
8
|
+
elsif defined?(RAILS_DEFAULT_LOGGER)
|
9
|
+
RAILS_DEFAULT_LOGGER
|
10
|
+
end
|
11
|
+
|
12
|
+
def initialize(options={})
|
13
|
+
@quiet = options[:quiet]
|
14
|
+
Delayed::Job.min_priority = options[:min_priority] if options.has_key?(:min_priority)
|
15
|
+
Delayed::Job.max_priority = options[:max_priority] if options.has_key?(:max_priority)
|
16
|
+
end
|
17
|
+
|
18
|
+
def start
|
19
|
+
say "*** Starting job worker #{Delayed::Job.worker_name}"
|
20
|
+
|
21
|
+
trap('TERM') { say 'Exiting...'; $exit = true }
|
22
|
+
trap('INT') { say 'Exiting...'; $exit = true }
|
23
|
+
|
24
|
+
loop do
|
25
|
+
result = nil
|
26
|
+
|
27
|
+
realtime = Benchmark.realtime do
|
28
|
+
result = Delayed::Job.work_off
|
29
|
+
end
|
30
|
+
|
31
|
+
count = result.sum
|
32
|
+
|
33
|
+
break if $exit
|
34
|
+
|
35
|
+
if count.zero?
|
36
|
+
sleep(SLEEP)
|
37
|
+
else
|
38
|
+
say "#{count} jobs processed at %.4f j/s, %d failed ..." % [count / realtime, result.last]
|
39
|
+
end
|
40
|
+
|
41
|
+
break if $exit
|
42
|
+
end
|
43
|
+
|
44
|
+
ensure
|
45
|
+
Delayed::Job.clear_locks!
|
46
|
+
end
|
47
|
+
|
48
|
+
def say(text)
|
49
|
+
puts text unless @quiet
|
50
|
+
logger.info text if logger
|
51
|
+
end
|
52
|
+
|
53
|
+
end
|
54
|
+
end
|
data/lib/delayed_job.rb
ADDED
@@ -0,0 +1,13 @@
|
|
1
|
+
autoload :ActiveRecord, 'activerecord'
|
2
|
+
|
3
|
+
require File.dirname(__FILE__) + '/delayed/message_sending'
|
4
|
+
require File.dirname(__FILE__) + '/delayed/performable_method'
|
5
|
+
require File.dirname(__FILE__) + '/delayed/job'
|
6
|
+
require File.dirname(__FILE__) + '/delayed/worker'
|
7
|
+
|
8
|
+
Object.send(:include, Delayed::MessageSending)
|
9
|
+
Module.send(:include, Delayed::MessageSending::ClassMethods)
|
10
|
+
|
11
|
+
if defined?(Merb::Plugins)
|
12
|
+
Merb::Plugins.add_rakefiles File.dirname(__FILE__) / '..' / 'tasks' / 'tasks'
|
13
|
+
end
|
data/spec/database.rb
ADDED
@@ -0,0 +1,44 @@
|
|
1
|
+
$:.unshift(File.dirname(__FILE__) + '/../lib')
|
2
|
+
$:.unshift(File.dirname(__FILE__) + '/../../rspec/lib')
|
3
|
+
|
4
|
+
require 'rubygems'
|
5
|
+
require 'active_record'
|
6
|
+
gem 'sqlite3-ruby'
|
7
|
+
|
8
|
+
require File.dirname(__FILE__) + '/../init'
|
9
|
+
require 'spec'
|
10
|
+
|
11
|
+
ActiveRecord::Base.logger = Logger.new('/tmp/dj.log')
|
12
|
+
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => '/tmp/jobs.sqlite')
|
13
|
+
ActiveRecord::Migration.verbose = false
|
14
|
+
ActiveRecord::Base.default_timezone = :utc if Time.zone.nil?
|
15
|
+
|
16
|
+
ActiveRecord::Schema.define do
|
17
|
+
|
18
|
+
create_table :delayed_jobs, :force => true do |table|
|
19
|
+
table.integer :priority, :default => 0
|
20
|
+
table.integer :attempts, :default => 0
|
21
|
+
table.text :handler
|
22
|
+
table.string :last_error
|
23
|
+
table.datetime :run_at
|
24
|
+
table.datetime :locked_at
|
25
|
+
table.string :locked_by
|
26
|
+
table.datetime :failed_at
|
27
|
+
table.string :runner
|
28
|
+
table.timestamps
|
29
|
+
end
|
30
|
+
|
31
|
+
create_table :stories, :force => true do |table|
|
32
|
+
table.string :text
|
33
|
+
end
|
34
|
+
|
35
|
+
end
|
36
|
+
|
37
|
+
|
38
|
+
# Purely useful for test cases...
|
39
|
+
class Story < ActiveRecord::Base
|
40
|
+
def tell; text; end
|
41
|
+
def whatever(n, _); tell*n; end
|
42
|
+
|
43
|
+
handle_asynchronously :whatever
|
44
|
+
end
|
@@ -0,0 +1,128 @@
|
|
1
|
+
require File.dirname(__FILE__) + '/database'
|
2
|
+
|
3
|
+
class SimpleJob
|
4
|
+
cattr_accessor :runs; self.runs = 0
|
5
|
+
def perform; @@runs += 1; end
|
6
|
+
end
|
7
|
+
|
8
|
+
class RandomRubyObject
|
9
|
+
def say_hello
|
10
|
+
'hello'
|
11
|
+
end
|
12
|
+
end
|
13
|
+
|
14
|
+
class ErrorObject
|
15
|
+
|
16
|
+
def throw
|
17
|
+
raise ActiveRecord::RecordNotFound, '...'
|
18
|
+
false
|
19
|
+
end
|
20
|
+
|
21
|
+
end
|
22
|
+
|
23
|
+
class StoryReader
|
24
|
+
|
25
|
+
def read(story)
|
26
|
+
"Epilog: #{story.tell}"
|
27
|
+
end
|
28
|
+
|
29
|
+
end
|
30
|
+
|
31
|
+
class StoryReader
|
32
|
+
|
33
|
+
def read(story)
|
34
|
+
"Epilog: #{story.tell}"
|
35
|
+
end
|
36
|
+
|
37
|
+
end
|
38
|
+
|
39
|
+
describe 'random ruby objects' do
|
40
|
+
before { Delayed::Job.delete_all }
|
41
|
+
|
42
|
+
it "should respond_to :send_later method" do
|
43
|
+
|
44
|
+
RandomRubyObject.new.respond_to?(:send_later)
|
45
|
+
|
46
|
+
end
|
47
|
+
|
48
|
+
it "should raise a ArgumentError if send_later is called but the target method doesn't exist" do
|
49
|
+
lambda { RandomRubyObject.new.send_later(:method_that_deos_not_exist) }.should raise_error(NoMethodError)
|
50
|
+
end
|
51
|
+
|
52
|
+
it "should add a new entry to the job table when send_later is called on it" do
|
53
|
+
Delayed::Job.count.should == 0
|
54
|
+
|
55
|
+
RandomRubyObject.new.send_later(:to_s)
|
56
|
+
|
57
|
+
Delayed::Job.count.should == 1
|
58
|
+
end
|
59
|
+
|
60
|
+
it "should add a new entry to the job table when send_later is called on the class" do
|
61
|
+
Delayed::Job.count.should == 0
|
62
|
+
|
63
|
+
RandomRubyObject.send_later(:to_s)
|
64
|
+
|
65
|
+
Delayed::Job.count.should == 1
|
66
|
+
end
|
67
|
+
|
68
|
+
it "should run get the original method executed when the job is performed" do
|
69
|
+
|
70
|
+
RandomRubyObject.new.send_later(:say_hello)
|
71
|
+
|
72
|
+
Delayed::Job.count.should == 1
|
73
|
+
end
|
74
|
+
|
75
|
+
it "should ignore ActiveRecord::RecordNotFound errors because they are permanent" do
|
76
|
+
|
77
|
+
ErrorObject.new.send_later(:throw)
|
78
|
+
|
79
|
+
Delayed::Job.count.should == 1
|
80
|
+
|
81
|
+
Delayed::Job.reserve_and_run_one_job
|
82
|
+
|
83
|
+
Delayed::Job.count.should == 0
|
84
|
+
|
85
|
+
end
|
86
|
+
|
87
|
+
it "should store the object as string if its an active record" do
|
88
|
+
story = Story.create :text => 'Once upon...'
|
89
|
+
story.send_later(:tell)
|
90
|
+
|
91
|
+
job = Delayed::Job.find(:first)
|
92
|
+
job.payload_object.class.should == Delayed::PerformableMethod
|
93
|
+
job.payload_object.object.should == "AR:Story:#{story.id}"
|
94
|
+
job.payload_object.method.should == :tell
|
95
|
+
job.payload_object.args.should == []
|
96
|
+
job.payload_object.perform.should == 'Once upon...'
|
97
|
+
end
|
98
|
+
|
99
|
+
it "should store arguments as string if they an active record" do
|
100
|
+
|
101
|
+
story = Story.create :text => 'Once upon...'
|
102
|
+
|
103
|
+
reader = StoryReader.new
|
104
|
+
reader.send_later(:read, story)
|
105
|
+
|
106
|
+
job = Delayed::Job.find(:first)
|
107
|
+
job.payload_object.class.should == Delayed::PerformableMethod
|
108
|
+
job.payload_object.method.should == :read
|
109
|
+
job.payload_object.args.should == ["AR:Story:#{story.id}"]
|
110
|
+
job.payload_object.perform.should == 'Epilog: Once upon...'
|
111
|
+
end
|
112
|
+
|
113
|
+
it "should call send later on methods which are wrapped with handle_asynchronously" do
|
114
|
+
story = Story.create :text => 'Once upon...'
|
115
|
+
|
116
|
+
Delayed::Job.count.should == 0
|
117
|
+
|
118
|
+
story.whatever(1, 5)
|
119
|
+
|
120
|
+
Delayed::Job.count.should == 1
|
121
|
+
job = Delayed::Job.find(:first)
|
122
|
+
job.payload_object.class.should == Delayed::PerformableMethod
|
123
|
+
job.payload_object.method.should == :whatever_without_send_later
|
124
|
+
job.payload_object.args.should == [1, 5]
|
125
|
+
job.payload_object.perform.should == 'Once upon...'
|
126
|
+
end
|
127
|
+
|
128
|
+
end
|
data/spec/job_spec.rb
ADDED
@@ -0,0 +1,381 @@
|
|
1
|
+
require File.dirname(__FILE__) + '/database'
|
2
|
+
|
3
|
+
class SimpleJob
|
4
|
+
cattr_accessor :runs; self.runs = 0
|
5
|
+
def perform; @@runs += 1; end
|
6
|
+
end
|
7
|
+
|
8
|
+
class ErrorJob
|
9
|
+
cattr_accessor :runs; self.runs = 0
|
10
|
+
def perform; raise 'did not work'; end
|
11
|
+
end
|
12
|
+
|
13
|
+
module M
|
14
|
+
class ModuleJob
|
15
|
+
cattr_accessor :runs; self.runs = 0
|
16
|
+
def perform; @@runs += 1; end
|
17
|
+
end
|
18
|
+
|
19
|
+
end
|
20
|
+
|
21
|
+
describe Delayed::Job do
|
22
|
+
before do
|
23
|
+
Delayed::Job.max_priority = nil
|
24
|
+
Delayed::Job.min_priority = nil
|
25
|
+
|
26
|
+
Delayed::Job.delete_all
|
27
|
+
end
|
28
|
+
|
29
|
+
before(:each) do
|
30
|
+
SimpleJob.runs = 0
|
31
|
+
end
|
32
|
+
|
33
|
+
it "should set run_at automatically if not set" do
|
34
|
+
Delayed::Job.create(:payload_object => ErrorJob.new ).run_at.should_not == nil
|
35
|
+
end
|
36
|
+
|
37
|
+
it "should not set run_at automatically if already set" do
|
38
|
+
later = 5.minutes.from_now
|
39
|
+
Delayed::Job.create(:payload_object => ErrorJob.new, :run_at => later).run_at.should == later
|
40
|
+
end
|
41
|
+
|
42
|
+
it "should raise ArgumentError when handler doesn't respond_to :perform" do
|
43
|
+
lambda { Delayed::Job.enqueue(Object.new) }.should raise_error(ArgumentError)
|
44
|
+
end
|
45
|
+
|
46
|
+
it "should increase count after enqueuing items" do
|
47
|
+
Delayed::Job.enqueue SimpleJob.new
|
48
|
+
Delayed::Job.count.should == 1
|
49
|
+
end
|
50
|
+
|
51
|
+
it "should be able to set priority when enqueuing items" do
|
52
|
+
Delayed::Job.enqueue SimpleJob.new, :priority => 5
|
53
|
+
Delayed::Job.first.priority.should == 5
|
54
|
+
end
|
55
|
+
|
56
|
+
it "should be able to set run_at when enqueuing items" do
|
57
|
+
later = (Delayed::Job.db_time_now+5.minutes)
|
58
|
+
Delayed::Job.enqueue SimpleJob.new, :priority => 5, :run_at => later
|
59
|
+
|
60
|
+
# use be close rather than equal to because millisecond values cn be lost in DB round trip
|
61
|
+
Delayed::Job.first.run_at.should be_close(later, 1)
|
62
|
+
end
|
63
|
+
|
64
|
+
it "should call perform on jobs when running work_off" do
|
65
|
+
SimpleJob.runs.should == 0
|
66
|
+
|
67
|
+
Delayed::Job.enqueue SimpleJob.new
|
68
|
+
Delayed::Job.work_off
|
69
|
+
|
70
|
+
SimpleJob.runs.should == 1
|
71
|
+
end
|
72
|
+
|
73
|
+
it "should work with eval jobs" do
|
74
|
+
$eval_job_ran = false
|
75
|
+
|
76
|
+
Delayed::Job.enqueue do <<-JOB
|
77
|
+
$eval_job_ran = true
|
78
|
+
JOB
|
79
|
+
end
|
80
|
+
|
81
|
+
Delayed::Job.work_off
|
82
|
+
|
83
|
+
$eval_job_ran.should == true
|
84
|
+
end
|
85
|
+
|
86
|
+
it "should work with jobs in modules" do
|
87
|
+
M::ModuleJob.runs.should == 0
|
88
|
+
|
89
|
+
Delayed::Job.enqueue M::ModuleJob.new
|
90
|
+
Delayed::Job.work_off
|
91
|
+
|
92
|
+
M::ModuleJob.runs.should == 1
|
93
|
+
end
|
94
|
+
|
95
|
+
it "should re-schedule by about 1 second at first and increment this more and more minutes when it fails to execute properly" do
|
96
|
+
Delayed::Job.enqueue ErrorJob.new
|
97
|
+
Delayed::Job.work_off(1)
|
98
|
+
|
99
|
+
job = Delayed::Job.find(:first)
|
100
|
+
|
101
|
+
job.last_error.should =~ /did not work/
|
102
|
+
job.last_error.should =~ /job_spec.rb:10:in `perform'/
|
103
|
+
job.attempts.should == 1
|
104
|
+
|
105
|
+
job.run_at.should > Delayed::Job.db_time_now - 10.minutes
|
106
|
+
job.run_at.should < Delayed::Job.db_time_now + 10.minutes
|
107
|
+
end
|
108
|
+
|
109
|
+
it "should raise an DeserializationError when the job class is totally unknown" do
|
110
|
+
|
111
|
+
job = Delayed::Job.new
|
112
|
+
job['handler'] = "--- !ruby/object:JobThatDoesNotExist {}"
|
113
|
+
|
114
|
+
lambda { job.payload_object.perform }.should raise_error(Delayed::DeserializationError)
|
115
|
+
end
|
116
|
+
|
117
|
+
it "should try to load the class when it is unknown at the time of the deserialization" do
|
118
|
+
job = Delayed::Job.new
|
119
|
+
job['handler'] = "--- !ruby/object:JobThatDoesNotExist {}"
|
120
|
+
|
121
|
+
job.should_receive(:attempt_to_load).with('JobThatDoesNotExist').and_return(true)
|
122
|
+
|
123
|
+
lambda { job.payload_object.perform }.should raise_error(Delayed::DeserializationError)
|
124
|
+
end
|
125
|
+
|
126
|
+
it "should try include the namespace when loading unknown objects" do
|
127
|
+
job = Delayed::Job.new
|
128
|
+
job['handler'] = "--- !ruby/object:Delayed::JobThatDoesNotExist {}"
|
129
|
+
job.should_receive(:attempt_to_load).with('Delayed::JobThatDoesNotExist').and_return(true)
|
130
|
+
lambda { job.payload_object.perform }.should raise_error(Delayed::DeserializationError)
|
131
|
+
end
|
132
|
+
|
133
|
+
it "should also try to load structs when they are unknown (raises TypeError)" do
|
134
|
+
job = Delayed::Job.new
|
135
|
+
job['handler'] = "--- !ruby/struct:JobThatDoesNotExist {}"
|
136
|
+
|
137
|
+
job.should_receive(:attempt_to_load).with('JobThatDoesNotExist').and_return(true)
|
138
|
+
|
139
|
+
lambda { job.payload_object.perform }.should raise_error(Delayed::DeserializationError)
|
140
|
+
end
|
141
|
+
|
142
|
+
it "should try include the namespace when loading unknown structs" do
|
143
|
+
job = Delayed::Job.new
|
144
|
+
job['handler'] = "--- !ruby/struct:Delayed::JobThatDoesNotExist {}"
|
145
|
+
|
146
|
+
job.should_receive(:attempt_to_load).with('Delayed::JobThatDoesNotExist').and_return(true)
|
147
|
+
lambda { job.payload_object.perform }.should raise_error(Delayed::DeserializationError)
|
148
|
+
end
|
149
|
+
|
150
|
+
it "should be failed if it failed more than MAX_ATTEMPTS times and we don't want to destroy jobs" do
|
151
|
+
default = Delayed::Job.destroy_failed_jobs
|
152
|
+
Delayed::Job.destroy_failed_jobs = false
|
153
|
+
|
154
|
+
@job = Delayed::Job.create :payload_object => SimpleJob.new, :attempts => 50
|
155
|
+
@job.reload.failed_at.should == nil
|
156
|
+
@job.reschedule 'FAIL'
|
157
|
+
@job.reload.failed_at.should_not == nil
|
158
|
+
|
159
|
+
Delayed::Job.destroy_failed_jobs = default
|
160
|
+
end
|
161
|
+
|
162
|
+
it "should be destroyed if it failed more than MAX_ATTEMPTS times and we want to destroy jobs" do
|
163
|
+
default = Delayed::Job.destroy_failed_jobs
|
164
|
+
Delayed::Job.destroy_failed_jobs = true
|
165
|
+
|
166
|
+
@job = Delayed::Job.create :payload_object => SimpleJob.new, :attempts => 50
|
167
|
+
@job.should_receive(:destroy)
|
168
|
+
@job.reschedule 'FAIL'
|
169
|
+
|
170
|
+
Delayed::Job.destroy_failed_jobs = default
|
171
|
+
end
|
172
|
+
|
173
|
+
it "should never find failed jobs" do
|
174
|
+
@job = Delayed::Job.create :payload_object => SimpleJob.new, :attempts => 50, :failed_at => Delayed::Job.db_time_now
|
175
|
+
Delayed::Job.find_available(1).length.should == 0
|
176
|
+
end
|
177
|
+
|
178
|
+
context "when another worker is already performing an task, it" do
|
179
|
+
|
180
|
+
before :each do
|
181
|
+
Delayed::Job.worker_name = 'worker1'
|
182
|
+
@job = Delayed::Job.create :payload_object => SimpleJob.new, :locked_by => 'worker1', :locked_at => Delayed::Job.db_time_now - 5.minutes
|
183
|
+
end
|
184
|
+
|
185
|
+
it "should not allow a second worker to get exclusive access" do
|
186
|
+
@job.lock_exclusively!(4.hours, 'worker2').should == false
|
187
|
+
end
|
188
|
+
|
189
|
+
it "should allow a second worker to get exclusive access if the timeout has passed" do
|
190
|
+
@job.lock_exclusively!(1.minute, 'worker2').should == true
|
191
|
+
end
|
192
|
+
|
193
|
+
it "should be able to get access to the task if it was started more then max_age ago" do
|
194
|
+
@job.locked_at = Delayed::Job.send(:db_time_now) - 5.hours
|
195
|
+
@job.save
|
196
|
+
|
197
|
+
@job.lock_exclusively! 4.hours, 'worker2'
|
198
|
+
@job.reload
|
199
|
+
@job.locked_by.should == 'worker2'
|
200
|
+
@job.locked_at.should > 1.minute.ago
|
201
|
+
end
|
202
|
+
|
203
|
+
it "should not be found by another worker" do
|
204
|
+
Delayed::Job.worker_name = 'worker2'
|
205
|
+
|
206
|
+
Delayed::Job.find_available(1, 6.minutes).length.should == 0
|
207
|
+
end
|
208
|
+
|
209
|
+
it "should be found by another worker if the time has expired" do
|
210
|
+
Delayed::Job.worker_name = 'worker2'
|
211
|
+
|
212
|
+
Delayed::Job.find_available(1, 4.minutes).length.should == 1
|
213
|
+
end
|
214
|
+
|
215
|
+
it "should be able to get exclusive access again when the worker name is the same" do
|
216
|
+
@job.lock_exclusively! 5.minutes, 'worker1'
|
217
|
+
@job.lock_exclusively! 5.minutes, 'worker1'
|
218
|
+
@job.lock_exclusively! 5.minutes, 'worker1'
|
219
|
+
end
|
220
|
+
end
|
221
|
+
|
222
|
+
context "#name" do
|
223
|
+
it "should be the class name of the job that was enqueued" do
|
224
|
+
Delayed::Job.create(:payload_object => ErrorJob.new ).name.should == 'ErrorJob'
|
225
|
+
end
|
226
|
+
|
227
|
+
it "should be the method that will be called if its a performable method object" do
|
228
|
+
Delayed::Job.send_later(:clear_locks!)
|
229
|
+
Delayed::Job.last.name.should == 'Delayed::Job.clear_locks!'
|
230
|
+
|
231
|
+
end
|
232
|
+
it "should be the instance method that will be called if its a performable method object" do
|
233
|
+
story = Story.create :text => "..."
|
234
|
+
|
235
|
+
story.send_later(:save)
|
236
|
+
|
237
|
+
Delayed::Job.last.name.should == 'Story#save'
|
238
|
+
end
|
239
|
+
end
|
240
|
+
|
241
|
+
context "worker prioritization" do
|
242
|
+
|
243
|
+
before(:each) do
|
244
|
+
Delayed::Job.max_priority = nil
|
245
|
+
Delayed::Job.min_priority = nil
|
246
|
+
end
|
247
|
+
|
248
|
+
it "should only work_off jobs that are >= min_priority" do
|
249
|
+
Delayed::Job.min_priority = -5
|
250
|
+
Delayed::Job.max_priority = 5
|
251
|
+
SimpleJob.runs.should == 0
|
252
|
+
|
253
|
+
Delayed::Job.enqueue SimpleJob.new, :priority => -10
|
254
|
+
Delayed::Job.enqueue SimpleJob.new, :priority => 0
|
255
|
+
Delayed::Job.work_off
|
256
|
+
|
257
|
+
SimpleJob.runs.should == 1
|
258
|
+
end
|
259
|
+
|
260
|
+
it "should only work_off jobs that are <= max_priority" do
|
261
|
+
Delayed::Job.min_priority = -5
|
262
|
+
Delayed::Job.max_priority = 5
|
263
|
+
SimpleJob.runs.should == 0
|
264
|
+
|
265
|
+
Delayed::Job.enqueue SimpleJob.new, :priority => 10
|
266
|
+
Delayed::Job.enqueue SimpleJob.new, :priority => 0
|
267
|
+
|
268
|
+
Delayed::Job.work_off
|
269
|
+
|
270
|
+
SimpleJob.runs.should == 1
|
271
|
+
end
|
272
|
+
|
273
|
+
end
|
274
|
+
|
275
|
+
context "when pulling jobs off the queue for processing, it" do
|
276
|
+
before(:each) do
|
277
|
+
@job = Delayed::Job.create(
|
278
|
+
:payload_object => SimpleJob.new,
|
279
|
+
:locked_by => 'worker1',
|
280
|
+
:locked_at => Delayed::Job.db_time_now - 5.minutes)
|
281
|
+
end
|
282
|
+
|
283
|
+
it "should leave the queue in a consistent state and not run the job if locking fails" do
|
284
|
+
SimpleJob.runs.should == 0
|
285
|
+
@job.stub!(:lock_exclusively!).with(any_args).once.and_return(false)
|
286
|
+
Delayed::Job.should_receive(:find_available).once.and_return([@job])
|
287
|
+
Delayed::Job.work_off(1)
|
288
|
+
SimpleJob.runs.should == 0
|
289
|
+
end
|
290
|
+
|
291
|
+
end
|
292
|
+
|
293
|
+
context "while running alongside other workers that locked jobs, it" do
|
294
|
+
before(:each) do
|
295
|
+
Delayed::Job.worker_name = 'worker1'
|
296
|
+
Delayed::Job.create(:payload_object => SimpleJob.new, :locked_by => 'worker1', :locked_at => (Delayed::Job.db_time_now - 1.minutes))
|
297
|
+
Delayed::Job.create(:payload_object => SimpleJob.new, :locked_by => 'worker2', :locked_at => (Delayed::Job.db_time_now - 1.minutes))
|
298
|
+
Delayed::Job.create(:payload_object => SimpleJob.new)
|
299
|
+
Delayed::Job.create(:payload_object => SimpleJob.new, :locked_by => 'worker1', :locked_at => (Delayed::Job.db_time_now - 1.minutes))
|
300
|
+
end
|
301
|
+
|
302
|
+
it "should ingore locked jobs from other workers" do
|
303
|
+
Delayed::Job.worker_name = 'worker3'
|
304
|
+
SimpleJob.runs.should == 0
|
305
|
+
Delayed::Job.work_off
|
306
|
+
SimpleJob.runs.should == 1 # runs the one open job
|
307
|
+
end
|
308
|
+
|
309
|
+
it "should find our own jobs regardless of locks" do
|
310
|
+
Delayed::Job.worker_name = 'worker1'
|
311
|
+
SimpleJob.runs.should == 0
|
312
|
+
Delayed::Job.work_off
|
313
|
+
SimpleJob.runs.should == 3 # runs open job plus worker1 jobs that were already locked
|
314
|
+
end
|
315
|
+
end
|
316
|
+
|
317
|
+
context "while running with locked and expired jobs, it" do
|
318
|
+
before(:each) do
|
319
|
+
Delayed::Job.worker_name = 'worker1'
|
320
|
+
exp_time = Delayed::Job.db_time_now - (1.minutes + Delayed::Job::MAX_RUN_TIME)
|
321
|
+
Delayed::Job.create(:payload_object => SimpleJob.new, :locked_by => 'worker1', :locked_at => exp_time)
|
322
|
+
Delayed::Job.create(:payload_object => SimpleJob.new, :locked_by => 'worker2', :locked_at => (Delayed::Job.db_time_now - 1.minutes))
|
323
|
+
Delayed::Job.create(:payload_object => SimpleJob.new)
|
324
|
+
Delayed::Job.create(:payload_object => SimpleJob.new, :locked_by => 'worker1', :locked_at => (Delayed::Job.db_time_now - 1.minutes))
|
325
|
+
end
|
326
|
+
|
327
|
+
it "should only find unlocked and expired jobs" do
|
328
|
+
Delayed::Job.worker_name = 'worker3'
|
329
|
+
SimpleJob.runs.should == 0
|
330
|
+
Delayed::Job.work_off
|
331
|
+
SimpleJob.runs.should == 2 # runs the one open job and one expired job
|
332
|
+
end
|
333
|
+
|
334
|
+
it "should ignore locks when finding our own jobs" do
|
335
|
+
Delayed::Job.worker_name = 'worker1'
|
336
|
+
SimpleJob.runs.should == 0
|
337
|
+
Delayed::Job.work_off
|
338
|
+
SimpleJob.runs.should == 3 # runs open job plus worker1 jobs
|
339
|
+
# This is useful in the case of a crash/restart on worker1, but make sure multiple workers on the same host have unique names!
|
340
|
+
end
|
341
|
+
|
342
|
+
end
|
343
|
+
|
344
|
+
context "Different job runners" do
|
345
|
+
before :each do
|
346
|
+
@job1 = Delayed::Job.create! :payload_object => SimpleJob.new, :runner => 'runner1'
|
347
|
+
@job2 = Delayed::Job.create! :payload_object => SimpleJob.new, :runner => 'runner2'
|
348
|
+
@job3 = Delayed::Job.create! :payload_object => SimpleJob.new, :runner => nil
|
349
|
+
end
|
350
|
+
|
351
|
+
it "should only work off jobs assigned to themselves" do
|
352
|
+
Delayed::Job.runner_name = 'runner1'
|
353
|
+
SimpleJob.runs.should == 0
|
354
|
+
Delayed::Job.work_off
|
355
|
+
SimpleJob.runs.should == 1
|
356
|
+
|
357
|
+
SimpleJob.runs = 0
|
358
|
+
|
359
|
+
Delayed::Job.runner_name = 'runner2'
|
360
|
+
SimpleJob.runs.should == 0
|
361
|
+
Delayed::Job.work_off
|
362
|
+
SimpleJob.runs.should == 1
|
363
|
+
end
|
364
|
+
|
365
|
+
it "should not work off jobs not assigned to themselves" do
|
366
|
+
Delayed::Job.runner_name = 'runner3'
|
367
|
+
|
368
|
+
SimpleJob.runs.should == 0
|
369
|
+
Delayed::Job.work_off
|
370
|
+
SimpleJob.runs.should == 0
|
371
|
+
end
|
372
|
+
|
373
|
+
it "should run non-named runner jobs when the runner has no name set" do
|
374
|
+
Delayed::Job.runner_name = nil
|
375
|
+
|
376
|
+
SimpleJob.runs.should == 0
|
377
|
+
Delayed::Job.work_off
|
378
|
+
SimpleJob.runs.should == 1
|
379
|
+
end
|
380
|
+
end
|
381
|
+
end
|
data/spec/story_spec.rb
ADDED
@@ -0,0 +1,17 @@
|
|
1
|
+
require File.dirname(__FILE__) + '/database'
|
2
|
+
|
3
|
+
describe "A story" do
|
4
|
+
|
5
|
+
before(:all) do
|
6
|
+
@story = Story.create :text => "Once upon a time..."
|
7
|
+
end
|
8
|
+
|
9
|
+
it "should be shared" do
|
10
|
+
@story.tell.should == 'Once upon a time...'
|
11
|
+
end
|
12
|
+
|
13
|
+
it "should not return its result if it storytelling is delayed" do
|
14
|
+
@story.send_later(:tell).should_not == 'Once upon a time...'
|
15
|
+
end
|
16
|
+
|
17
|
+
end
|
data/tasks/jobs.rake
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
require File.join(File.dirname(__FILE__), 'tasks')
|
data/tasks/tasks.rb
ADDED
@@ -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
|
metadata
ADDED
@@ -0,0 +1,75 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: andrewtimberlake-delayed_job
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 1.8.4.1
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- "Tobias L\xC3\xBCtke"
|
8
|
+
- Andrew Timberlake
|
9
|
+
autorequire:
|
10
|
+
bindir: bin
|
11
|
+
cert_chain: []
|
12
|
+
|
13
|
+
date: 2010-02-10 00:00:00 +02:00
|
14
|
+
default_executable:
|
15
|
+
dependencies: []
|
16
|
+
|
17
|
+
description: Delayed_job (or DJ) encapsulates the common pattern of asynchronously executing longer tasks in the background. It is a direct extraction from Shopify where the job table is responsible for a multitude of core tasks.
|
18
|
+
email: andrew@andrewtimberlake.com
|
19
|
+
executables: []
|
20
|
+
|
21
|
+
extensions: []
|
22
|
+
|
23
|
+
extra_rdoc_files:
|
24
|
+
- README.textile
|
25
|
+
files:
|
26
|
+
- .gitignore
|
27
|
+
- MIT-LICENSE
|
28
|
+
- README.textile
|
29
|
+
- generators/delayed_job_migration/delayed_job_migration_generator.rb
|
30
|
+
- generators/delayed_job_migration/templates/migration.rb
|
31
|
+
- init.rb
|
32
|
+
- lib/delayed/job.rb
|
33
|
+
- lib/delayed/message_sending.rb
|
34
|
+
- lib/delayed/performable_method.rb
|
35
|
+
- lib/delayed/worker.rb
|
36
|
+
- lib/delayed_job.rb
|
37
|
+
- spec/database.rb
|
38
|
+
- spec/delayed_method_spec.rb
|
39
|
+
- spec/job_spec.rb
|
40
|
+
- spec/story_spec.rb
|
41
|
+
- tasks/jobs.rake
|
42
|
+
- tasks/tasks.rb
|
43
|
+
has_rdoc: true
|
44
|
+
homepage: http://github.com/andrewtimberlake/delayed_job
|
45
|
+
licenses: []
|
46
|
+
|
47
|
+
post_install_message:
|
48
|
+
rdoc_options:
|
49
|
+
- --charset=UTF-8
|
50
|
+
require_paths:
|
51
|
+
- lib
|
52
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
53
|
+
requirements:
|
54
|
+
- - ">="
|
55
|
+
- !ruby/object:Gem::Version
|
56
|
+
version: "0"
|
57
|
+
version:
|
58
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
59
|
+
requirements:
|
60
|
+
- - ">="
|
61
|
+
- !ruby/object:Gem::Version
|
62
|
+
version: "0"
|
63
|
+
version:
|
64
|
+
requirements: []
|
65
|
+
|
66
|
+
rubyforge_project:
|
67
|
+
rubygems_version: 1.3.5
|
68
|
+
signing_key:
|
69
|
+
specification_version: 3
|
70
|
+
summary: Database-backed asynchronous priority queue system -- Extracted from Shopify
|
71
|
+
test_files:
|
72
|
+
- spec/database.rb
|
73
|
+
- spec/delayed_method_spec.rb
|
74
|
+
- spec/job_spec.rb
|
75
|
+
- spec/story_spec.rb
|