delayed_job_unique_key 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (43) hide show
  1. data/MIT-LICENSE +20 -0
  2. data/README.textile +246 -0
  3. data/contrib/delayed_job.monitrc +14 -0
  4. data/contrib/delayed_job_multiple.monitrc +23 -0
  5. data/lib/delayed/backend/base.rb +152 -0
  6. data/lib/delayed/backend/shared_spec.rb +566 -0
  7. data/lib/delayed/command.rb +101 -0
  8. data/lib/delayed/deserialization_error.rb +4 -0
  9. data/lib/delayed/lifecycle.rb +84 -0
  10. data/lib/delayed/message_sending.rb +54 -0
  11. data/lib/delayed/performable_mailer.rb +21 -0
  12. data/lib/delayed/performable_method.rb +33 -0
  13. data/lib/delayed/plugin.rb +15 -0
  14. data/lib/delayed/plugins/clear_locks.rb +15 -0
  15. data/lib/delayed/psych_ext.rb +75 -0
  16. data/lib/delayed/railtie.rb +16 -0
  17. data/lib/delayed/recipes.rb +50 -0
  18. data/lib/delayed/serialization/active_record.rb +19 -0
  19. data/lib/delayed/syck_ext.rb +34 -0
  20. data/lib/delayed/tasks.rb +11 -0
  21. data/lib/delayed/worker.rb +222 -0
  22. data/lib/delayed/yaml_ext.rb +10 -0
  23. data/lib/delayed_job.rb +22 -0
  24. data/lib/generators/delayed_job/delayed_job_generator.rb +11 -0
  25. data/lib/generators/delayed_job/templates/script +5 -0
  26. data/recipes/delayed_job.rb +1 -0
  27. data/spec/autoloaded/clazz.rb +7 -0
  28. data/spec/autoloaded/instance_clazz.rb +6 -0
  29. data/spec/autoloaded/instance_struct.rb +6 -0
  30. data/spec/autoloaded/struct.rb +7 -0
  31. data/spec/delayed/backend/test.rb +113 -0
  32. data/spec/delayed/serialization/test.rb +0 -0
  33. data/spec/fixtures/bad_alias.yml +1 -0
  34. data/spec/lifecycle_spec.rb +107 -0
  35. data/spec/message_sending_spec.rb +116 -0
  36. data/spec/performable_mailer_spec.rb +46 -0
  37. data/spec/performable_method_spec.rb +89 -0
  38. data/spec/sample_jobs.rb +75 -0
  39. data/spec/spec_helper.rb +45 -0
  40. data/spec/test_backend_spec.rb +13 -0
  41. data/spec/worker_spec.rb +19 -0
  42. data/spec/yaml_ext_spec.rb +41 -0
  43. metadata +197 -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,246 @@
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
+ "Follow us on Twitter":https://twitter.com/delayedjob to get updates and notices about new releases.
16
+
17
+
18
+ h2. Installation
19
+
20
+ delayed_job 2.1 only supports Rails 3.0+. See the "2.0 branch":https://github.com/collectiveidea/delayed_job/tree/v2.0 for Rails 2.
21
+
22
+ To install, add delayed_job to your @Gemfile@ and run `bundle install`:
23
+
24
+ <pre>
25
+ gem 'delayed_job'
26
+ </pre>
27
+
28
+ After delayed_job is installed, you will need to setup the backend.
29
+
30
+ h3. Backends
31
+
32
+ delayed_job supports multiple backends for storing the job queue. "See the wiki for other backends":http://wiki.github.com/collectiveidea/delayed_job/backends besides Active Record.
33
+
34
+ The default is Active Record, which requires a jobs table.
35
+
36
+ <pre>
37
+ $ script/rails generate delayed_job
38
+ $ rake db:migrate
39
+ </pre>
40
+
41
+ h2. Queuing Jobs
42
+
43
+ Call @.delay.method(params)@ on any object and it will be processed in the background.
44
+
45
+ <pre>
46
+ # without delayed_job
47
+ @user.activate!(@device)
48
+
49
+ # with delayed_job
50
+ @user.delay.activate!(@device)
51
+ </pre>
52
+
53
+ If a method should always be run in the background, you can call @#handle_asynchronously@ after the method declaration:
54
+
55
+ <pre>
56
+ class Device
57
+ def deliver
58
+ # long running method
59
+ end
60
+ handle_asynchronously :deliver
61
+ end
62
+
63
+ device = Device.new
64
+ device.deliver
65
+ </pre>
66
+
67
+ handle_asynchronously can take as options anything you can pass to delay. In addition the values can be Proc objects allowing call time evaluation of the value. For some examples:
68
+
69
+ <pre>
70
+ class LongTasks
71
+ def send_mailer
72
+ # Some other code
73
+ end
74
+ handle_asynchronously :send_mailer, :priority => 20
75
+
76
+ def in_the_future
77
+ # Some other code
78
+ end
79
+ # 5.minutes.from_now will be evaluated when in_the_future is called
80
+ handle_asynchronously :in_the_future, :run_at => Proc.new { 5.minutes.from_now }
81
+
82
+ def self.when_to_run
83
+ 2.hours.from_now
84
+ end
85
+
86
+ def call_a_class_method
87
+ # Some other code
88
+ end
89
+ handle_asynchronously :call_a_class_method, :run_at => Proc.new { when_to_run }
90
+
91
+ attr_reader :how_important
92
+
93
+ def call_an_instance_method
94
+ # Some other code
95
+ end
96
+ handle_asynchronously :call_an_instance_method, :priority => Proc.new {|i| i.how_important }
97
+ end
98
+ </pre>
99
+
100
+ h3. Rails 3 Mailers
101
+
102
+ Due to how mailers are implemented in Rails 3, we had to do a little work around to get delayed_job to work.
103
+
104
+ <pre>
105
+ # without delayed_job
106
+ Notifier.signup(@user).deliver
107
+
108
+ # with delayed_job
109
+ Notifier.delay.signup(@user)
110
+ </pre>
111
+
112
+ Remove the @.deliver@ method to make it work. It's not ideal, but it's the best we could do for now.
113
+
114
+ h2. Running Jobs
115
+
116
+ @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`.
117
+
118
+ <pre>
119
+ $ RAILS_ENV=production script/delayed_job start
120
+ $ RAILS_ENV=production script/delayed_job stop
121
+
122
+ # Runs two workers in separate processes.
123
+ $ RAILS_ENV=production script/delayed_job -n 2 start
124
+ $ RAILS_ENV=production script/delayed_job stop
125
+ </pre>
126
+
127
+ 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.
128
+
129
+ You can also invoke @rake jobs:work@ which will start working off jobs. You can cancel the rake task with @CTRL-C@.
130
+
131
+ h2. Custom Jobs
132
+
133
+ 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.
134
+
135
+ <pre>
136
+ class NewsletterJob < Struct.new(:text, :emails)
137
+ def perform
138
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
139
+ end
140
+ end
141
+
142
+ Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.find(:all).collect(&:email))
143
+ </pre>
144
+
145
+ h2. Hooks
146
+
147
+ You can define hooks on your job that will be called at different stages in the process:
148
+
149
+ <pre>
150
+ class ParanoidNewsletterJob < NewsletterJob
151
+ def enqueue(job)
152
+ record_stat 'newsletter_job/enqueue'
153
+ end
154
+
155
+ def perform
156
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
157
+ end
158
+
159
+ def before(job)
160
+ record_stat 'newsletter_job/start'
161
+ end
162
+
163
+ def after(job)
164
+ record_stat 'newsletter_job/after'
165
+ end
166
+
167
+ def success(job)
168
+ record_stat 'newsletter_job/success'
169
+ end
170
+
171
+ def error(job, exception)
172
+ notify_hoptoad(exception)
173
+ end
174
+
175
+ def failure
176
+ page_sysadmin_in_the_middle_of_the_night
177
+ end
178
+ end
179
+ </pre>
180
+
181
+ h2. Gory Details
182
+
183
+ The library evolves around a delayed_jobs table which looks as follows:
184
+
185
+ <pre>
186
+ create_table :delayed_jobs, :force => true do |table|
187
+ table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
188
+ table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
189
+ table.text :handler # YAML-encoded string of the object that will do work
190
+ table.text :last_error # reason for last failure (See Note below)
191
+ table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future.
192
+ table.datetime :locked_at # Set when a client is working on this object
193
+ table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
194
+ table.string :locked_by # Who is working on this object (if locked)
195
+ table.timestamps
196
+ end
197
+ </pre>
198
+
199
+ On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries.
200
+
201
+ The default Worker.max_attempts is 25. After this, the job either deleted (default), or left in the database with "failed_at" set.
202
+ With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours.
203
+
204
+ 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
205
+ make sure your job doesn't exceed this time. You should set this to the longest time you think the job could take.
206
+
207
+ By default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set
208
+ Delayed::Worker.destroy_failed_jobs = false. The failed jobs will be marked with non-null failed_at.
209
+
210
+ By default all jobs are scheduled with priority = 0, which is top priority. You can change this by setting Delayed::Worker.default_priority to something else. Lower numbers have higher priority.
211
+
212
+ It is possible to disable delayed jobs for testing purposes. Set Delayed::Worker.delay_jobs = false to execute all jobs realtime.
213
+
214
+ Here is an example of changing job parameters in Rails:
215
+
216
+ <pre>
217
+ # config/initializers/delayed_job_config.rb
218
+ Delayed::Worker.destroy_failed_jobs = false
219
+ Delayed::Worker.sleep_delay = 60
220
+ Delayed::Worker.max_attempts = 3
221
+ Delayed::Worker.max_run_time = 5.minutes
222
+ Delayed::Worker.delay_jobs = !Rails.env.test?
223
+ </pre>
224
+
225
+ h3. Cleaning up
226
+
227
+ You can invoke @rake jobs:clear@ to delete all jobs in the queue.
228
+
229
+ h2. Mailing List
230
+
231
+ Join us on the "mailing list":http://groups.google.com/group/delayed_job
232
+
233
+ h2. How to contribute
234
+
235
+ If you find what looks like a bug:
236
+
237
+ # Search the "mailing list":http://groups.google.com/group/delayed_job to see if anyone else had the same issue.
238
+ # Check the "GitHub issue tracker":http://github.com/collectiveidea/delayed_job/issues/ to see if anyone else has reported issue.
239
+ # If you don't see anything, create an issue with information on how to reproduce it.
240
+
241
+ If you want to contribute an enhancement or a fix:
242
+
243
+ # Fork the project on github.
244
+ # Make your changes with tests.
245
+ # Commit the changes without making changes to the Rakefile or any other files that aren't related to your enhancement or fix
246
+ # Send a pull request.
@@ -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,152 @@
1
+ module Delayed
2
+ module Backend
3
+ module Base
4
+ def self.included(base)
5
+ base.extend ClassMethods
6
+ end
7
+
8
+ module ClassMethods
9
+ # Add a job to the queue
10
+ def enqueue(*args)
11
+ options = {
12
+ :priority => Delayed::Worker.default_priority
13
+ }.merge!(args.extract_options!)
14
+
15
+ options[:payload_object] ||= args.shift
16
+
17
+ if args.size > 0
18
+ warn "[DEPRECATION] Passing multiple arguments to `#enqueue` is deprecated. Pass a hash with :priority and :run_at."
19
+ options[:priority] = args.first || options[:priority]
20
+ options[:unique_key] = options[:unique_key]
21
+ options[:run_at] = args[1]
22
+ end
23
+
24
+ unless options[:payload_object].respond_to?(:perform)
25
+ raise ArgumentError, 'Cannot enqueue items which do not respond to perform'
26
+ end
27
+
28
+ if Delayed::Worker.delay_jobs
29
+ self.new(options).tap do |job|
30
+ Delayed::Worker.lifecycle.run_callbacks(:enqueue, job) do
31
+ job.hook(:enqueue)
32
+ job.save
33
+ end
34
+ end
35
+ else
36
+ Delayed::Job.new(:payload_object => options[:payload_object]).tap do |job|
37
+ job.invoke_job
38
+ end
39
+ end
40
+ end
41
+
42
+ def reserve(worker, max_run_time = Worker.max_run_time)
43
+ # We get up to 5 jobs from the db. In case we cannot get exclusive access to a job we try the next.
44
+ # this leads to a more even distribution of jobs across the worker processes
45
+ find_available(worker.name, 5, max_run_time).detect do |job|
46
+ job.lock_exclusively!(max_run_time, worker.name)
47
+ end
48
+ end
49
+
50
+ # Hook method that is called before a new worker is forked
51
+ def before_fork
52
+ end
53
+
54
+ # Hook method that is called after a new worker is forked
55
+ def after_fork
56
+ end
57
+
58
+ def work_off(num = 100)
59
+ warn "[DEPRECATION] `Delayed::Job.work_off` is deprecated. Use `Delayed::Worker.new.work_off instead."
60
+ Delayed::Worker.new.work_off(num)
61
+ end
62
+ end
63
+
64
+ def failed?
65
+ failed_at
66
+ end
67
+ alias_method :failed, :failed?
68
+
69
+ ParseObjectFromYaml = /\!ruby\/\w+\:([^\s]+)/
70
+
71
+ def name
72
+ @name ||= payload_object.respond_to?(:display_name) ?
73
+ payload_object.display_name :
74
+ payload_object.class.name
75
+ rescue DeserializationError
76
+ ParseObjectFromYaml.match(handler)[1]
77
+ end
78
+
79
+ def payload_object=(object)
80
+ @payload_object = object
81
+ self.handler = object.to_yaml
82
+ end
83
+
84
+ def payload_object
85
+ @payload_object ||= YAML.load(self.handler)
86
+ rescue TypeError, LoadError, NameError, ArgumentError => e
87
+ raise DeserializationError,
88
+ "Job failed to load: #{e.message}. Handler: #{handler.inspect}"
89
+ end
90
+
91
+ def invoke_job
92
+ Delayed::Worker.lifecycle.run_callbacks(:invoke_job, self) do
93
+ begin
94
+ hook :before
95
+ payload_object.perform
96
+ hook :success
97
+ rescue Exception => e
98
+ hook :error, e
99
+ raise e
100
+ ensure
101
+ hook :after
102
+ end
103
+ end
104
+ end
105
+
106
+ # Unlock this job (note: not saved to DB)
107
+ def unlock
108
+ self.locked_at = nil
109
+ self.locked_by = nil
110
+ end
111
+
112
+ def hook(name, *args)
113
+ if payload_object.respond_to?(name)
114
+ method = payload_object.method(name)
115
+ method.arity == 0 ? method.call : method.call(self, *args)
116
+ end
117
+ rescue DeserializationError
118
+ # do nothing
119
+ end
120
+
121
+ def reschedule_at
122
+ payload_object.respond_to?(:reschedule_at) ?
123
+ payload_object.reschedule_at(self.class.db_time_now, attempts) :
124
+ self.class.db_time_now + (attempts ** 4) + 5
125
+ end
126
+
127
+ def max_attempts
128
+ payload_object.max_attempts if payload_object.respond_to?(:max_attempts)
129
+ end
130
+
131
+ def fail!
132
+ update_attributes(:failed_at => self.class.db_time_now)
133
+ end
134
+
135
+ protected
136
+
137
+ def set_default_run_at
138
+ self.run_at ||= self.class.db_time_now
139
+ end
140
+
141
+ def check_unique_key
142
+ return true if !self.respond_to?(:unique_key) || self.unique_key.blank?
143
+ self.class.where(:unique_key => self.unique_key, :locked_at => nil).first.nil?
144
+ end
145
+
146
+ # Call during reload operation to clear out internal state
147
+ def reset
148
+ @payload_object = nil
149
+ end
150
+ end
151
+ end
152
+ end