delayed-job-ajaycb 2.0.10

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