yetanothernguyen-delayed_job 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (38) 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/generators/delayed_job/delayed_job_generator.rb +22 -0
  6. data/generators/delayed_job/templates/migration.rb +21 -0
  7. data/generators/delayed_job/templates/script +5 -0
  8. data/lib/delayed/backend/active_record.rb +92 -0
  9. data/lib/delayed/backend/base.rb +135 -0
  10. data/lib/delayed/backend/data_mapper.rb +125 -0
  11. data/lib/delayed/backend/mongo_mapper.rb +110 -0
  12. data/lib/delayed/command.rb +112 -0
  13. data/lib/delayed/deserialization_error.rb +4 -0
  14. data/lib/delayed/message_sending.rb +53 -0
  15. data/lib/delayed/performable_method.rb +62 -0
  16. data/lib/delayed/railtie.rb +10 -0
  17. data/lib/delayed/recipes.rb +50 -0
  18. data/lib/delayed/tasks.rb +15 -0
  19. data/lib/delayed/worker.rb +179 -0
  20. data/lib/delayed_job.rb +15 -0
  21. data/rails/init.rb +5 -0
  22. data/recipes/delayed_job.rb +1 -0
  23. data/spec/backend/active_record_job_spec.rb +46 -0
  24. data/spec/backend/data_mapper_job_spec.rb +16 -0
  25. data/spec/backend/mongo_mapper_job_spec.rb +94 -0
  26. data/spec/backend/shared_backend_spec.rb +341 -0
  27. data/spec/delayed_method_spec.rb +46 -0
  28. data/spec/message_sending_spec.rb +89 -0
  29. data/spec/performable_method_spec.rb +53 -0
  30. data/spec/sample_jobs.rb +26 -0
  31. data/spec/setup/active_record.rb +33 -0
  32. data/spec/setup/data_mapper.rb +8 -0
  33. data/spec/setup/mongo_mapper.rb +17 -0
  34. data/spec/spec_helper.rb +28 -0
  35. data/spec/story_spec.rb +17 -0
  36. data/spec/worker_spec.rb +237 -0
  37. data/tasks/jobs.rake +1 -0
  38. metadata +328 -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
+ 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
+ This version is for Rails 2.x only. For rails 3 support, install delayed_job 2.1.
18
+
19
+ To install as a gem, add the following to @config/environment.rb@:
20
+
21
+ <pre>
22
+ config.gem 'delayed_job', :version => '~>2.0.4'
23
+ </pre>
24
+
25
+ Rake tasks are not automatically loaded from gems, so you'll need to add the following to your Rakefile:
26
+
27
+ <pre>
28
+ begin
29
+ gem 'delayed_job', '~>2.0.4'
30
+ require 'delayed/tasks'
31
+ rescue LoadError
32
+ STDERR.puts "Run `rake gems:install` to install delayed_job"
33
+ end
34
+ </pre>
35
+
36
+ To install as a plugin:
37
+
38
+ <pre>
39
+ script/plugin install git://github.com/collectiveidea/delayed_job.git -r v2.0
40
+ </pre>
41
+
42
+ After delayed_job is installed, you will need to setup the backend.
43
+
44
+ h2. Backends
45
+
46
+ delayed_job supports multiple backends for storing the job queue. There are currently implementations for Active Record, MongoMapper, and DataMapper.
47
+
48
+ h3. Active Record
49
+
50
+ The default is Active Record, which requires a jobs table.
51
+
52
+ <pre>
53
+ $ script/generate delayed_job
54
+ $ rake db:migrate
55
+ </pre>
56
+
57
+ h3. MongoMapper
58
+
59
+ You must use @MongoMapper.setup@ in the initializer:
60
+
61
+ <pre>
62
+ config = YAML::load(File.read(Rails.root.join('config/mongo.yml')))
63
+ MongoMapper.setup(config, Rails.env)
64
+
65
+ Delayed::Worker.backend = :mongo_mapper
66
+ </pre>
67
+
68
+ h3. DataMapper
69
+
70
+ <pre>
71
+ # config/initializers/delayed_job.rb
72
+ Delayed::Worker.backend = :data_mapper
73
+ Delayed::Worker.backend.auto_upgrade!
74
+ </pre>
75
+
76
+ h2. Queuing Jobs
77
+
78
+ Call @.delay.method(params)@ on any object and it will be processed in the background.
79
+
80
+ <pre>
81
+ # without delayed_job
82
+ Notifier.deliver_signup(@user)
83
+
84
+ # with delayed_job
85
+ Notifier.delay.deliver_signup @user
86
+ </pre>
87
+
88
+ If a method should always be run in the background, you can call @#handle_asynchronously@ after the method declaration:
89
+
90
+ <pre>
91
+ class Device
92
+ def deliver
93
+ # long running method
94
+ end
95
+ handle_asynchronously :deliver
96
+ end
97
+
98
+ device = Device.new
99
+ device.deliver
100
+ </pre>
101
+
102
+ 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:
103
+
104
+ <pre>
105
+ class LongTasks
106
+ def send_mailer
107
+ # Some other code
108
+ end
109
+ handle_asynchronously :send_mailer, :priority => 20
110
+
111
+ def in_the_future
112
+ # Some other code
113
+ end
114
+ # 5.minutes.from_now will be evaluated when in_the_future is called
115
+ handle_asynchronously :in_the_future, :run_at => Proc.new { 5.minutes.from_now }
116
+
117
+ def self.when_to_run
118
+ 2.hours.from_now
119
+ end
120
+
121
+ def call_a_class_method
122
+ # Some other code
123
+ end
124
+ handle_asynchronously :call_a_class_method, :run_at => Proc.new { when_to_run }
125
+
126
+ attr_reader :how_important
127
+
128
+ def call_an_instance_method
129
+ # Some other code
130
+ end
131
+ handle_asynchronously :call_an_instance_method, :priority => Proc.new {|i| i.how_important }
132
+ end
133
+ </pre>
134
+
135
+ h2. Running Jobs
136
+
137
+ @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`.
138
+
139
+ <pre>
140
+ $ RAILS_ENV=production script/delayed_job start
141
+ $ RAILS_ENV=production script/delayed_job stop
142
+
143
+ # Runs two workers in separate processes.
144
+ $ RAILS_ENV=production script/delayed_job -n 2 start
145
+ $ RAILS_ENV=production script/delayed_job stop
146
+ </pre>
147
+
148
+ 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.
149
+
150
+ You can also invoke @rake jobs:work@ which will start working off jobs. You can cancel the rake task with @CTRL-C@.
151
+
152
+ h2. Custom Jobs
153
+
154
+ 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.
155
+
156
+ <pre>
157
+ class NewsletterJob < Struct.new(:text, :emails)
158
+ def perform
159
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
160
+ end
161
+ end
162
+
163
+ Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.find(:all).collect(&:email))
164
+ </pre>
165
+
166
+ You can also add an optional on_permanent_failure method which will run if the job has failed too many times to be retried:
167
+
168
+ <pre>
169
+ class ParanoidNewsletterJob < NewsletterJob
170
+ def perform
171
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
172
+ end
173
+
174
+ def on_permanent_failure
175
+ page_sysadmin_in_the_middle_of_the_night
176
+ end
177
+ end
178
+ </pre>
179
+
180
+ h2. Gory Details
181
+
182
+ The library evolves around a delayed_jobs table which looks as follows:
183
+
184
+ <pre>
185
+ create_table :delayed_jobs, :force => true do |table|
186
+ table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
187
+ table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
188
+ table.text :handler # YAML-encoded string of the object that will do work
189
+ table.text :last_error # reason for last failure (See Note below)
190
+ table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future.
191
+ table.datetime :locked_at # Set when a client is working on this object
192
+ table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
193
+ table.string :locked_by # Who is working on this object (if locked)
194
+ table.timestamps
195
+ end
196
+ </pre>
197
+
198
+ On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries.
199
+
200
+ The default Worker.max_attempts is 25. After this, the job either deleted (default), or left in the database with "failed_at" set.
201
+ With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours.
202
+
203
+ 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
204
+ make sure your job doesn't exceed this time. You should set this to the longest time you think the job could take.
205
+
206
+ By default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set
207
+ Delayed::Worker.destroy_failed_jobs = false. The failed jobs will be marked with non-null failed_at.
208
+
209
+ Here is an example of changing job parameters in Rails:
210
+
211
+ <pre>
212
+ # config/initializers/delayed_job_config.rb
213
+ Delayed::Worker.destroy_failed_jobs = false
214
+ Delayed::Worker.sleep_delay = 60
215
+ Delayed::Worker.max_attempts = 3
216
+ Delayed::Worker.max_run_time = 5.minutes
217
+ </pre>
218
+
219
+ h3. Cleaning up
220
+
221
+ You can invoke @rake jobs:clear@ to delete all jobs in the queue.
222
+
223
+ h2. Mailing List
224
+
225
+ Join us on the mailing list at http://groups.google.com/group/delayed_job
226
+
227
+ h2. How to contribute
228
+
229
+ If you find what looks like a bug:
230
+
231
+ # Check the GitHub issue tracker to see if anyone else has had the same issue.
232
+ http://github.com/collectiveidea/delayed_job/issues/
233
+ # If you don't see anything, create an issue with information on how to reproduce it.
234
+
235
+ If you want to contribute an enhancement or a fix:
236
+
237
+ # Fork the project on github.
238
+ http://github.com/collectiveidea/delayed_job/
239
+ # Make your changes with tests.
240
+ # Commit the changes without making changes to the Rakefile, VERSION, or any other files that aren't related to your enhancement or fix
241
+ # Send a pull request.
242
+
243
+ h3. Changelog
244
+
245
+ See http://wiki.github.com/collectiveidea/delayed_job/changelog for a list of changes.
246
+
@@ -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,22 @@
1
+ class DelayedJobGenerator < Rails::Generator::Base
2
+ default_options :skip_migration => false
3
+
4
+ def manifest
5
+ record do |m|
6
+ m.template 'script', 'script/delayed_job', :chmod => 0755
7
+ if !options[:skip_migration] && defined?(ActiveRecord)
8
+ m.migration_template "migration.rb", 'db/migrate',
9
+ :migration_file_name => "create_delayed_jobs"
10
+ end
11
+ end
12
+ end
13
+
14
+ protected
15
+
16
+ def add_options!(opt)
17
+ opt.separator ''
18
+ opt.separator 'Options:'
19
+ opt.on("--skip-migration", "Don't generate a migration") { |v| options[:skip_migration] = v }
20
+ end
21
+
22
+ end
@@ -0,0 +1,21 @@
1
+ class CreateDelayedJobs < ActiveRecord::Migration
2
+ def self.up
3
+ create_table :delayed_jobs, :force => true do |table|
4
+ table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
5
+ table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
6
+ table.text :handler # YAML-encoded string of the object that will do work
7
+ table.text :last_error # reason for last failure (See Note below)
8
+ table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future.
9
+ table.datetime :locked_at # Set when a client is working on this object
10
+ table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
11
+ table.string :locked_by # Who is working on this object (if locked)
12
+ table.timestamps
13
+ end
14
+
15
+ add_index :delayed_jobs, [:priority, :run_at], :name => 'delayed_jobs_priority'
16
+ end
17
+
18
+ def self.down
19
+ drop_table :delayed_jobs
20
+ end
21
+ end
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment'))
4
+ require 'delayed/command'
5
+ Delayed::Command.new(ARGV).daemonize
@@ -0,0 +1,92 @@
1
+ require 'active_record'
2
+
3
+ class ActiveRecord::Base
4
+ def self.load_for_delayed_job(id)
5
+ if id
6
+ find(id)
7
+ else
8
+ super
9
+ end
10
+ end
11
+
12
+ def dump_for_delayed_job
13
+ "#{self.class};#{id}"
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
+ named_scope :ready_to_run, lambda {|worker_name, max_run_time|
29
+ {:conditions => ['(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]}
30
+ }
31
+ named_scope :by_priority, :order => 'priority ASC, run_at ASC'
32
+
33
+ def self.after_fork
34
+ ::ActiveRecord::Base.connection.reconnect!
35
+ end
36
+
37
+ # When a worker is exiting, make sure we don't have any locked jobs.
38
+ def self.clear_locks!(worker_name)
39
+ update_all("locked_by = null, locked_at = null", ["locked_by = ?", worker_name])
40
+ end
41
+
42
+ # Find a few candidate jobs to run (in case some immediately get locked by others).
43
+ def self.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time)
44
+ scope = self.ready_to_run(worker_name, max_run_time)
45
+ scope = scope.scoped(:conditions => ['priority >= ?', Worker.min_priority]) if Worker.min_priority
46
+ scope = scope.scoped(:conditions => ['priority <= ?', Worker.max_priority]) if Worker.max_priority
47
+
48
+ ::ActiveRecord::Base.silence do
49
+ scope.by_priority.all(:limit => limit)
50
+ end
51
+ end
52
+
53
+ # Lock this job for this worker.
54
+ # Returns true if we have the lock, false otherwise.
55
+ def lock_exclusively!(max_run_time, worker)
56
+ now = self.class.db_time_now
57
+ affected_rows = if locked_by != worker
58
+ # We don't own this job so we will update the locked_by name and the locked_at
59
+ 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])
60
+ else
61
+ # We already own this job, this may happen if the job queue crashes.
62
+ # Simply resume and update the locked_at
63
+ self.class.update_all(["locked_at = ?", now], ["id = ? and locked_by = ?", id, worker])
64
+ end
65
+ if affected_rows == 1
66
+ self.locked_at = now
67
+ self.locked_by = worker
68
+ self.locked_at_will_change!
69
+ self.locked_by_will_change!
70
+ return true
71
+ else
72
+ return false
73
+ end
74
+ end
75
+
76
+ # Get the current time (GMT or local depending on DB)
77
+ # Note: This does not ping the DB to get the time, so all your clients
78
+ # must have syncronized clocks.
79
+ def self.db_time_now
80
+ if Time.zone
81
+ Time.zone.now
82
+ elsif ::ActiveRecord::Base.default_timezone == :utc
83
+ Time.now.utc
84
+ else
85
+ Time.now
86
+ end
87
+ end
88
+
89
+ end
90
+ end
91
+ end
92
+ end