delayed_job_with_named_queues 2.0.7.1

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