delayed_job_hooked 2.1.5

Sign up to get free protection for your applications and to get access to all the features.
@@ -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.
@@ -0,0 +1,243 @@
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
+ 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.
18
+
19
+ To install, add delayed_job to your @Gemfile@ and run `bundle install`:
20
+
21
+ <pre>
22
+ gem 'delayed_job'
23
+ </pre>
24
+
25
+ After delayed_job is installed, you will need to setup the backend.
26
+
27
+ h3. Backends
28
+
29
+ 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.
30
+
31
+ The default is Active Record, which requires a jobs table.
32
+
33
+ <pre>
34
+ $ script/rails generate delayed_job
35
+ $ rake db:migrate
36
+ </pre>
37
+
38
+ h2. Queuing Jobs
39
+
40
+ Call @.delay.method(params)@ on any object and it will be processed in the background.
41
+
42
+ <pre>
43
+ # without delayed_job
44
+ @user.activate!(@device)
45
+
46
+ # with delayed_job
47
+ @user.delay.activate!(@device)
48
+ </pre>
49
+
50
+ If a method should always be run in the background, you can call @#handle_asynchronously@ after the method declaration:
51
+
52
+ <pre>
53
+ class Device
54
+ def deliver
55
+ # long running method
56
+ end
57
+ handle_asynchronously :deliver
58
+ end
59
+
60
+ device = Device.new
61
+ device.deliver
62
+ </pre>
63
+
64
+ 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:
65
+
66
+ <pre>
67
+ class LongTasks
68
+ def send_mailer
69
+ # Some other code
70
+ end
71
+ handle_asynchronously :send_mailer, :priority => 20
72
+
73
+ def in_the_future
74
+ # Some other code
75
+ end
76
+ # 5.minutes.from_now will be evaluated when in_the_future is called
77
+ handle_asynchronously :in_the_future, :run_at => Proc.new { 5.minutes.from_now }
78
+
79
+ def self.when_to_run
80
+ 2.hours.from_now
81
+ end
82
+
83
+ def call_a_class_method
84
+ # Some other code
85
+ end
86
+ handle_asynchronously :call_a_class_method, :run_at => Proc.new { when_to_run }
87
+
88
+ attr_reader :how_important
89
+
90
+ def call_an_instance_method
91
+ # Some other code
92
+ end
93
+ handle_asynchronously :call_an_instance_method, :priority => Proc.new {|i| i.how_important }
94
+ end
95
+ </pre>
96
+
97
+ h3. Rails 3 Mailers
98
+
99
+ Due to how mailers are implemented in Rails 3, we had to do a little work around to get delayed_job to work.
100
+
101
+ <pre>
102
+ # without delayed_job
103
+ Notifier.signup(@user).deliver
104
+
105
+ # with delayed_job
106
+ Notifier.delay.signup(@user)
107
+ </pre>
108
+
109
+ Remove the @.deliver@ method to make it work. It's not ideal, but it's the best we could do for now.
110
+
111
+ h2. Running Jobs
112
+
113
+ @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`.
114
+
115
+ <pre>
116
+ $ RAILS_ENV=production script/delayed_job start
117
+ $ RAILS_ENV=production script/delayed_job stop
118
+
119
+ # Runs two workers in separate processes.
120
+ $ RAILS_ENV=production script/delayed_job -n 2 start
121
+ $ RAILS_ENV=production script/delayed_job stop
122
+ </pre>
123
+
124
+ 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.
125
+
126
+ You can also invoke @rake jobs:work@ which will start working off jobs. You can cancel the rake task with @CTRL-C@.
127
+
128
+ h2. Custom Jobs
129
+
130
+ 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.
131
+
132
+ <pre>
133
+ class NewsletterJob < Struct.new(:text, :emails)
134
+ def perform
135
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
136
+ end
137
+ end
138
+
139
+ Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.find(:all).collect(&:email))
140
+ </pre>
141
+
142
+ h2. Hooks
143
+
144
+ You can define hooks on your job that will be called at different stages in the process:
145
+
146
+ <pre>
147
+ class ParanoidNewsletterJob < NewsletterJob
148
+ def enqueue(job)
149
+ record_stat 'newsletter_job/enqueue'
150
+ end
151
+
152
+ def perform
153
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
154
+ end
155
+
156
+ def before(job)
157
+ record_stat 'newsletter_job/start'
158
+ end
159
+
160
+ def after(job)
161
+ record_stat 'newsletter_job/after'
162
+ end
163
+
164
+ def success(job)
165
+ record_stat 'newsletter_job/success'
166
+ end
167
+
168
+ def error(job, exception)
169
+ notify_hoptoad(exception)
170
+ end
171
+
172
+ def failure
173
+ page_sysadmin_in_the_middle_of_the_night
174
+ end
175
+ end
176
+ </pre>
177
+
178
+ h2. Gory Details
179
+
180
+ The library evolves around a delayed_jobs table which looks as follows:
181
+
182
+ <pre>
183
+ create_table :delayed_jobs, :force => true do |table|
184
+ table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
185
+ table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
186
+ table.text :handler # YAML-encoded string of the object that will do work
187
+ table.text :last_error # reason for last failure (See Note below)
188
+ table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future.
189
+ table.datetime :locked_at # Set when a client is working on this object
190
+ table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
191
+ table.string :locked_by # Who is working on this object (if locked)
192
+ table.timestamps
193
+ end
194
+ </pre>
195
+
196
+ On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries.
197
+
198
+ The default Worker.max_attempts is 25. After this, the job either deleted (default), or left in the database with "failed_at" set.
199
+ With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours.
200
+
201
+ 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
202
+ make sure your job doesn't exceed this time. You should set this to the longest time you think the job could take.
203
+
204
+ By default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set
205
+ Delayed::Worker.destroy_failed_jobs = false. The failed jobs will be marked with non-null failed_at.
206
+
207
+ 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.
208
+
209
+ It is possible to disable delayed jobs for testing purposes. Set Delayed::Worker.delay_jobs = false to execute all jobs realtime.
210
+
211
+ Here is an example of changing job parameters in Rails:
212
+
213
+ <pre>
214
+ # config/initializers/delayed_job_config.rb
215
+ Delayed::Worker.destroy_failed_jobs = false
216
+ Delayed::Worker.sleep_delay = 60
217
+ Delayed::Worker.max_attempts = 3
218
+ Delayed::Worker.max_run_time = 5.minutes
219
+ Delayed::Worker.delay_jobs = !Rails.env.test?
220
+ </pre>
221
+
222
+ h3. Cleaning up
223
+
224
+ You can invoke @rake jobs:clear@ to delete all jobs in the queue.
225
+
226
+ h2. Mailing List
227
+
228
+ Join us on the mailing list at http://groups.google.com/group/delayed_job
229
+
230
+ h2. How to contribute
231
+
232
+ If you find what looks like a bug:
233
+
234
+ # Search the "mailing list":http://groups.google.com/group/delayed_job to see if anyone else had the same issue.
235
+ # Check the "GitHub issue tracker":http://github.com/collectiveidea/delayed_job/issues/ to see if anyone else has reported issue.
236
+ # If you don't see anything, create an issue with information on how to reproduce it.
237
+
238
+ If you want to contribute an enhancement or a fix:
239
+
240
+ # Fork the project on github.
241
+ # Make your changes with tests.
242
+ # Commit the changes without making changes to the Rakefile or any other files that aren't related to your enhancement or fix
243
+ # 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,82 @@
1
+ require 'active_record'
2
+
3
+ module Delayed
4
+ module Backend
5
+ module ActiveRecord
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
+ include Delayed::Backend::Base
10
+ set_table_name :delayed_jobs
11
+
12
+ before_save :set_default_run_at
13
+
14
+ scope :ready_to_run, lambda {|worker_name, max_run_time|
15
+ 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])
16
+ }
17
+ scope :by_priority, order('priority ASC, run_at ASC')
18
+
19
+ def self.before_fork
20
+ ::ActiveRecord::Base.clear_all_connections!
21
+ end
22
+
23
+ def self.after_fork
24
+ ::ActiveRecord::Base.establish_connection
25
+ end
26
+
27
+ # When a worker is exiting, make sure we don't have any locked jobs.
28
+ def self.clear_locks!(worker_name)
29
+ update_all("locked_by = null, locked_at = null", ["locked_by = ?", worker_name])
30
+ end
31
+
32
+ # Find a few candidate jobs to run (in case some immediately get locked by others).
33
+ def self.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time)
34
+ scope = self.ready_to_run(worker_name, max_run_time)
35
+ scope = scope.scoped(:conditions => ['priority >= ?', Worker.min_priority]) if Worker.min_priority
36
+ scope = scope.scoped(:conditions => ['priority <= ?', Worker.max_priority]) if Worker.max_priority
37
+
38
+ ::ActiveRecord::Base.silence do
39
+ scope.by_priority.all(:limit => limit)
40
+ end
41
+ end
42
+
43
+ # Lock this job for this worker.
44
+ # Returns true if we have the lock, false otherwise.
45
+ def lock_exclusively!(max_run_time, worker)
46
+ now = self.class.db_time_now
47
+ affected_rows = if locked_by != worker
48
+ # We don't own this job so we will update the locked_by name and the locked_at
49
+ 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])
50
+ else
51
+ # We already own this job, this may happen if the job queue crashes.
52
+ # Simply resume and update the locked_at
53
+ self.class.update_all(["locked_at = ?", now], ["id = ? and locked_by = ?", id, worker])
54
+ end
55
+ if affected_rows == 1
56
+ self.locked_at = now
57
+ self.locked_by = worker
58
+ self.locked_at_will_change!
59
+ self.locked_by_will_change!
60
+ return true
61
+ else
62
+ return false
63
+ end
64
+ end
65
+
66
+ # Get the current time (GMT or local depending on DB)
67
+ # Note: This does not ping the DB to get the time, so all your clients
68
+ # must have syncronized clocks.
69
+ def self.db_time_now
70
+ if Time.zone
71
+ Time.zone.now
72
+ elsif ::ActiveRecord::Base.default_timezone == :utc
73
+ Time.now.utc
74
+ else
75
+ Time.now
76
+ end
77
+ end
78
+
79
+ end
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,128 @@
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[:run_at] = args[1]
21
+ end
22
+
23
+ unless options[:payload_object].respond_to?(:perform)
24
+ raise ArgumentError, 'Cannot enqueue items which do not respond to perform'
25
+ end
26
+
27
+ if Delayed::Worker.delay_jobs
28
+ self.create(options).tap do |job|
29
+ job.hook(:enqueue)
30
+ end
31
+ else
32
+ options[:payload_object].perform
33
+ end
34
+ end
35
+
36
+ def reserve(worker, max_run_time = Worker.max_run_time)
37
+ # We get up to 5 jobs from the db. In case we cannot get exclusive access to a job we try the next.
38
+ # this leads to a more even distribution of jobs across the worker processes
39
+ find_available(worker.name, 5, max_run_time).detect do |job|
40
+ job.lock_exclusively!(max_run_time, worker.name)
41
+ end
42
+ end
43
+
44
+ # Hook method that is called before a new worker is forked
45
+ def before_fork
46
+ end
47
+
48
+ # Hook method that is called after a new worker is forked
49
+ def after_fork
50
+ end
51
+
52
+ def work_off(num = 100)
53
+ warn "[DEPRECATION] `Delayed::Job.work_off` is deprecated. Use `Delayed::Worker.new.work_off instead."
54
+ Delayed::Worker.new.work_off(num)
55
+ end
56
+ end
57
+
58
+ def failed?
59
+ failed_at
60
+ end
61
+ alias_method :failed, :failed?
62
+
63
+ ParseObjectFromYaml = /\!ruby\/\w+\:([^\s]+)/
64
+
65
+ def name
66
+ @name ||= payload_object.respond_to?(:display_name) ?
67
+ payload_object.display_name :
68
+ payload_object.class.name
69
+ rescue DeserializationError
70
+ ParseObjectFromYaml.match(handler)[1]
71
+ end
72
+
73
+ def payload_object=(object)
74
+ @payload_object = object
75
+ self.handler = object.to_yaml
76
+ end
77
+
78
+ def payload_object
79
+ @payload_object ||= YAML.load(self.handler)
80
+ rescue TypeError, LoadError, NameError, ArgumentError => e
81
+ raise DeserializationError,
82
+ "Job failed to load: #{e.message}. Handler: #{handler.inspect}"
83
+ end
84
+
85
+ def invoke_job
86
+ hook :before
87
+ payload_object.perform
88
+ hook :success
89
+ rescue Exception => e
90
+ hook :error, e
91
+ raise e
92
+ ensure
93
+ hook :after
94
+ end
95
+
96
+ # Unlock this job (note: not saved to DB)
97
+ def unlock
98
+ self.locked_at = nil
99
+ self.locked_by = nil
100
+ end
101
+
102
+ def hook(name, *args)
103
+ if payload_object.respond_to?(name)
104
+ method = payload_object.method(name)
105
+ method.arity == 0 ? method.call : method.call(self, *args)
106
+ end
107
+ rescue DeserializationError
108
+ # do nothing
109
+ end
110
+
111
+ def reschedule_at
112
+ payload_object.respond_to?(:reschedule_at) ?
113
+ payload_object.reschedule_at(self.class.db_time_now, attempts) :
114
+ self.class.db_time_now + (attempts ** 4) + 5
115
+ end
116
+
117
+ def max_attempts
118
+ payload_object.max_attempts if payload_object.respond_to?(:max_attempts)
119
+ end
120
+
121
+ protected
122
+
123
+ def set_default_run_at
124
+ self.run_at ||= self.class.db_time_now
125
+ end
126
+ end
127
+ end
128
+ end