delayed_job_tgmerritt 4.0.7

Sign up to get free protection for your applications and to get access to all the features.
Files changed (54) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +208 -0
  3. data/CONTRIBUTING.md +27 -0
  4. data/LICENSE.md +20 -0
  5. data/README.md +424 -0
  6. data/Rakefile +15 -0
  7. data/contrib/delayed_job.monitrc +14 -0
  8. data/contrib/delayed_job_multiple.monitrc +34 -0
  9. data/contrib/delayed_job_rails_4.monitrc +14 -0
  10. data/contrib/delayed_job_rails_4_multiple.monitrc +34 -0
  11. data/delayed_job.gemspec +15 -0
  12. data/lib/delayed/backend/base.rb +159 -0
  13. data/lib/delayed/backend/shared_spec.rb +657 -0
  14. data/lib/delayed/command.rb +170 -0
  15. data/lib/delayed/compatibility.rb +27 -0
  16. data/lib/delayed/deserialization_error.rb +4 -0
  17. data/lib/delayed/exceptions.rb +12 -0
  18. data/lib/delayed/lifecycle.rb +85 -0
  19. data/lib/delayed/message_sending.rb +52 -0
  20. data/lib/delayed/performable_mailer.rb +22 -0
  21. data/lib/delayed/performable_method.rb +41 -0
  22. data/lib/delayed/plugin.rb +15 -0
  23. data/lib/delayed/plugins/clear_locks.rb +15 -0
  24. data/lib/delayed/psych_ext.rb +89 -0
  25. data/lib/delayed/railtie.rb +22 -0
  26. data/lib/delayed/recipes.rb +54 -0
  27. data/lib/delayed/serialization/active_record.rb +17 -0
  28. data/lib/delayed/syck_ext.rb +42 -0
  29. data/lib/delayed/tasks.rb +39 -0
  30. data/lib/delayed/worker.rb +312 -0
  31. data/lib/delayed/yaml_ext.rb +10 -0
  32. data/lib/delayed_job.rb +22 -0
  33. data/lib/generators/delayed_job/delayed_job_generator.rb +11 -0
  34. data/lib/generators/delayed_job/templates/script +5 -0
  35. data/recipes/delayed_job.rb +1 -0
  36. data/spec/autoloaded/clazz.rb +7 -0
  37. data/spec/autoloaded/instance_clazz.rb +6 -0
  38. data/spec/autoloaded/instance_struct.rb +7 -0
  39. data/spec/autoloaded/struct.rb +8 -0
  40. data/spec/daemons.rb +2 -0
  41. data/spec/delayed/backend/test.rb +117 -0
  42. data/spec/delayed/command_spec.rb +180 -0
  43. data/spec/delayed/serialization/test.rb +0 -0
  44. data/spec/helper.rb +85 -0
  45. data/spec/lifecycle_spec.rb +75 -0
  46. data/spec/message_sending_spec.rb +122 -0
  47. data/spec/performable_mailer_spec.rb +43 -0
  48. data/spec/performable_method_spec.rb +111 -0
  49. data/spec/psych_ext_spec.rb +12 -0
  50. data/spec/sample_jobs.rb +111 -0
  51. data/spec/test_backend_spec.rb +13 -0
  52. data/spec/worker_spec.rb +175 -0
  53. data/spec/yaml_ext_spec.rb +48 -0
  54. metadata +144 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: d2d68a79690257c56ec7043eaaa9ab1d92c6363c
4
+ data.tar.gz: b019e530f15c0441fd235ade34c5208bea685bdf
5
+ SHA512:
6
+ metadata.gz: 3c2042e0cd69ff03b184e4c9b74e12ebc9056c57afc92adc6d3f2232bfe52181fa460189c6d06f445f5d3a2c3937ca145137df63156855bdd0919009b9083e52
7
+ data.tar.gz: 1dd28225cd2d1906922fe9dcc804de561f83e4850e65f445e0aa4a3f20f5344858988e517a4cc3a54aacd3139f706204b390b2dcd54ccad1f46fde7da2aa599a
data/CHANGELOG.md ADDED
@@ -0,0 +1,208 @@
1
+ 4.0.6 - 2014-12-22
2
+ ==================
3
+ * Revert removing test files from the gem
4
+
5
+ 4.0.5 - 2014-12-22
6
+ ==================
7
+ * Support for Rails 4.2
8
+ * Allow user to override where DJ writes log output
9
+ * First attempt at automatic code reloading
10
+ * Clearer error message when ActiveRecord object no longer exists
11
+ * Various improvements to the README
12
+
13
+ 4.0.4 - 2014-09-24
14
+ ==================
15
+ * Fix using options passed into delayed_job command
16
+ * Add the ability to set a default queue for a custom job
17
+ * Add the ability to override the max_run_time on a custom job. MUST be lower than worker setting
18
+ * Psych YAML overrides are now exclusively used only when loading a job payload
19
+ * SLEEP_DELAY and READ_AHEAD can be set for the rake task
20
+ * Some updates for Rails 4.2 support
21
+
22
+ 4.0.3 - 2014-09-04
23
+ ==================
24
+ * Added --pools option to delayed_job command
25
+ * Removed a bunch of the Psych hacks
26
+ * Improved deserialization error reporting
27
+ * Misc bug fixes
28
+
29
+ 4.0.2 - 2014-06-24
30
+ ==================
31
+ * Add support for RSpec 3
32
+
33
+ 4.0.1 - 2014-04-12
34
+ ==================
35
+ * Update gemspec for Rails 4.1
36
+ * Make logger calls more universal
37
+ * Check that records are persisted? instead of new_record?
38
+
39
+ 4.0.0 - 2013-07-30
40
+ ==================
41
+ * Rails 4 compatibility
42
+ * Reverted threaded startup due to daemons incompatibilities
43
+ * Attempt to recover from job reservation errors
44
+
45
+ 4.0.0.beta2 - 2013-05-28
46
+ ========================
47
+ * Rails 4 compatibility
48
+ * Threaded startup script for faster multi-worker startup
49
+ * YAML compatibility changes
50
+ * Added jobs:check rake task
51
+
52
+ 4.0.0.beta1 - 2013-03-02
53
+ ========================
54
+ * Rails 4 compatibility
55
+
56
+ 3.0.5 - 2013-01-28
57
+ ==================
58
+ * Better job timeout error logging
59
+ * psych support for delayed_job_data_mapper deserialization
60
+ * User can configure the worker to raise a SignalException on TERM and/or INT
61
+ * Add the ability to run all available jobs and exit when complete
62
+
63
+ 3.0.4 - 2012-11-09
64
+ ==================
65
+ * Allow the app to specify a default queue name
66
+ * Capistrano script now allows user to specify the DJ command, allowing the user to add "bundle exec" if necessary
67
+ * Persisted record check is now more general
68
+
69
+ 3.0.3 - 2012-05-25
70
+ ==================
71
+ * Fix a bug where the worker would not respect the exit condition
72
+ * Properly handle sleep delay command line argument
73
+
74
+ 3.0.2 - 2012-04-02
75
+ ==================
76
+ * Fix deprecation warnings
77
+ * Raise ArgumentError if attempting to enqueue a performable method on an object that hasn't been persisted yet
78
+ * Allow the number of jobs read at a time to be configured from the command line using --read-ahead
79
+ * Allow custom logger to be configured through Delayed::Worker.logger
80
+ * Various documentation improvements
81
+
82
+ 3.0.1 - 2012-01-24
83
+ ==================
84
+ * Added RecordNotFound message to deserialization error
85
+ * Direct JRuby's yecht parser to syck extensions
86
+ * Updated psych extensions for better compatibility with ruby 1.9.2
87
+ * Updated syck extension for increased compatibility with class methods
88
+ * Test grooming
89
+
90
+ 3.0.0 - 2011-12-30
91
+ ==================
92
+ * New: Named queues
93
+ * New: Job/Worker lifecycle callbacks
94
+ * Change: daemons is no longer a runtime dependency
95
+ * Change: Active Record backend support is provided by a separate gem
96
+ * Change: Enqueue hook is called before jobs are saved so that they may be modified
97
+ * Fix problem deserializing models that use a custom primary key column
98
+ * Fix deserializing AR models when the object isn't in the default scope
99
+ * Fix hooks not getting called when delay_jobs is false
100
+
101
+ 2.1.4 - 2011-02-11
102
+ ==================
103
+ * Working around issues when psych is loaded, fixes issues with bundler 1.0.10 and Rails 3.0.4
104
+ * Added -p/--prefix option to help differentiate multiple delayed job workers on the same host.
105
+
106
+ 2.1.3 - 2011-01-20
107
+ ==================
108
+ * Revert worker contention fix due to regressions
109
+ * Added Delayed::Worker.delay_jobs flag to support running jobs immediately
110
+
111
+ 2.1.2 - 2010-12-01
112
+ ==================
113
+ * Remove contention between multiple workers by performing an update to lock a job before fetching it
114
+ * Job payloads may implement #max_attempts to control how many times it should be retried
115
+ * Fix for loading ActionMailer extension
116
+ * Added 'delayed_job_server_role' Capistrano variable to allow delayed_job to run on its own worker server
117
+ set :delayed_job_server_role, :worker
118
+ * Fix `rake jobs:work` so it outputs to the console
119
+
120
+ 2.1.1 - 2010-11-14
121
+ ==================
122
+ * Fix issue with worker name not getting properly set when locking a job
123
+ * Fixes for YAML serialization
124
+
125
+ 2.1.0 - 2010-11-14
126
+ ==================
127
+ * Added enqueue, before, after, success, error, and failure. See the README
128
+ * Remove Merb support
129
+ * Remove all non Active Record backends into separate gems. See https://github.com/collectiveidea/delayed_job/wiki/Backends
130
+ * remove rails 2 support. delayed_job 2.1 will only support Rails 3
131
+ * New pure-YAML serialization
132
+ * Added Rails 3 railtie and generator
133
+ * Changed @@sleep_delay to self.class.sleep_delay to be consistent with other class variable usage
134
+ * Added --sleep-delay command line option
135
+
136
+ 2.0.8 - Unreleased
137
+ ==================
138
+ * Backport fix for deserialization errors that bring down the daemon
139
+
140
+ 2.0.7 - 2011-02-10
141
+ ==================
142
+ * Fixed missing generators and recipes for Rails 2.x
143
+
144
+ 2.0.6 - 2011-01-20
145
+ ==================
146
+ * Revert worker contention fix due to regressions
147
+
148
+ 2.0.5 - 2010-12-01
149
+ ==================
150
+ * Added #reschedule_at hook on payload to determine when the job should be rescheduled [backported from 2.1]
151
+ * Added --sleep-delay command line option [backported from 2.1]
152
+ * Added 'delayed_job_server_role' Capistrano variable to allow delayed_job to run on its own worker server
153
+ set :delayed_job_server_role, :worker
154
+ * Changed AR backend to reserve jobs using an UPDATE query to reduce worker contention [backported from 2.1]
155
+
156
+ 2.0.4 - 2010-11-14
157
+ ==================
158
+ * Fix issue where dirty tracking prevented job from being properly unlocked
159
+ * Add delayed_job_args variable for Capistrano recipe to allow configuration of started workers (e.g. "-n 2 --max-priority 10")
160
+ * Added options to handle_asynchronously
161
+ * Added Delayed::Worker.default_priority
162
+ * Allow private methods to be delayed
163
+ * Fixes for Ruby 1.9
164
+ * Added -m command line option to start a monitor process
165
+ * normalize logging in worker
166
+ * Deprecate #send_later and #send_at in favor of new #delay method
167
+ * Added @#delay@ to Object that allows you to delay any method and pass options:
168
+ options = {:priority => 19, :run_at => 5.minutes.from_now}
169
+ UserMailer.delay(options).deliver_confirmation(@user)
170
+
171
+ 2.0.3 - 2010-04-16
172
+ ==================
173
+ * Fix initialization for Rails 2.x
174
+
175
+ 2.0.2 - 2010-04-08
176
+ ==================
177
+ * Fixes to Mongo Mapper backend [ "14be7a24":http://github.com/collectiveidea/delayed_job/commit/14be7a24, "dafd5f46":http://github.com/collectiveidea/delayed_job/commit/dafd5f46, "54d40913":http://github.com/collectiveidea/delayed_job/commit/54d40913 ]
178
+ * DataMapper backend performance improvements [ "93833cce":http://github.com/collectiveidea/delayed_job/commit/93833cce, "e9b1573e":http://github.com/collectiveidea/delayed_job/commit/e9b1573e, "37a16d11":http://github.com/collectiveidea/delayed_job/commit/37a16d11, "803f2bfa":http://github.com/collectiveidea/delayed_job/commit/803f2bfa ]
179
+ * Fixed Delayed::Command to create tmp/pids directory [ "8ec8ca41":http://github.com/collectiveidea/delayed_job/commit/8ec8ca41 ]
180
+ * Railtie to perform Rails 3 initialization [ "3e0fc41f":http://github.com/collectiveidea/delayed_job/commit/3e0fc41f ]
181
+ * Added on_permanent_failure hook [ "d2f14cd6":http://github.com/collectiveidea/delayed_job/commit/d2f14cd6 ]
182
+
183
+ 2.0.1 - 2010-04-03
184
+ ==================
185
+ * Bug fix for using ActiveRecord backend with daemon [martinbtt]
186
+
187
+ 2.0.0 - 2010-04-03
188
+ ==================
189
+ * Multiple backend support (See README for more details)
190
+ * Added MongoMapper backend [zbelzer, moneypools]
191
+ * Added DataMapper backend [lpetre]
192
+ * Reverse priority so the jobs table can be indexed. Lower numbers have higher priority. The default priority is 0, so increase it for jobs that are not important.
193
+ * Move most of the heavy lifting from Job to Worker (#work_off, #reschedule, #run, #min_priority, #max_priority, #max_run_time, #max_attempts, #worker_name) [albus522]
194
+ * Remove EvaledJob. Implement your own if you need this functionality.
195
+ * Only use Time.zone if it is set. Closes #20
196
+ * Fix for last_error recording when destroy_failed_jobs = false, max_attempts = 1
197
+ * Implemented worker name_prefix to maintain dynamic nature of pid detection
198
+ * Some Rails 3 compatibility fixes [fredwu]
199
+
200
+ 1.8.5 - 2010-03-15
201
+ ==================
202
+ * Set auto_flushing=true on Rails logger to fix logging in production
203
+ * Fix error message when trying to send_later on a method that doesn't exist
204
+ * Don't use rails_env in capistrano if it's not set. closes #22
205
+ * Delayed job should append to delayed_job.log not overwrite
206
+ * Version bump to 1.8.5
207
+ * fixing Time.now to be Time.zone.now if set to honor the app set local TimeZone
208
+ * Replaced @Worker::SLEEP@, @Job::MAX_ATTEMPTS@, and @Job::MAX_RUN_TIME@ with class methods that can be overridden.
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,27 @@
1
+ How to contribute
2
+ =================
3
+
4
+ If you find what looks like a bug:
5
+
6
+ * Search the "mailing list":http://groups.google.com/group/delayed_job to see
7
+ if anyone else had the same issue.
8
+ * Check the "GitHub issue tracker":http://github.com/collectiveidea/delayed_job/issues/
9
+ to see if anyone else has reported issue.
10
+ * Make sure you are using the latest version of delayed_job
11
+ ![Gem Version](https://badge.fury.io/rb/delayed_job.png)
12
+ * Make sure you are using the latest backend gem for delayed_job
13
+ * Active Record ![Gem Version](https://badge.fury.io/rb/delayed_job_active_record.png)
14
+ * Mongoid ![Gem Version](https://badge.fury.io/rb/delayed_job_mongoid.png)
15
+ * If you are still having an issue, create an issue including:
16
+ * Ruby version
17
+ * Gemfile.lock contents or at least major gem versions, such as Rails version
18
+ * Steps to reproduce the issue
19
+ * Full backtrace for any errors encountered
20
+
21
+ If you want to contribute an enhancement or a fix:
22
+
23
+ * Fork the project on GitHub.
24
+ * Make your changes with tests.
25
+ * Commit the changes without making changes to the Rakefile or any other files
26
+ that aren't related to your enhancement or fix.
27
+ * Send a pull request.
data/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2005 Tobias Lütke
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.md ADDED
@@ -0,0 +1,424 @@
1
+ Delayed::Job
2
+ ============
3
+ [![Gem Version](https://badge.fury.io/rb/delayed_job.png)][gem]
4
+ [![Build Status](https://travis-ci.org/collectiveidea/delayed_job.png?branch=master)][travis]
5
+ [![Dependency Status](https://gemnasium.com/collectiveidea/delayed_job.png?travis)][gemnasium]
6
+ [![Code Climate](https://codeclimate.com/github/collectiveidea/delayed_job.png)][codeclimate]
7
+ [![Coverage Status](https://coveralls.io/repos/collectiveidea/delayed_job/badge.png?branch=master)][coveralls]
8
+
9
+ [gem]: https://rubygems.org/gems/delayed_job
10
+ [travis]: https://travis-ci.org/collectiveidea/delayed_job
11
+ [gemnasium]: https://gemnasium.com/collectiveidea/delayed_job
12
+ [codeclimate]: https://codeclimate.com/github/collectiveidea/delayed_job
13
+ [coveralls]: https://coveralls.io/r/collectiveidea/delayed_job
14
+
15
+ Delayed::Job (or DJ) encapsulates the common pattern of asynchronously executing
16
+ longer tasks in the background.
17
+
18
+ It is a direct extraction from Shopify where the job table is responsible for a
19
+ multitude of core tasks. Amongst those tasks are:
20
+
21
+ * sending massive newsletters
22
+ * image resizing
23
+ * http downloads
24
+ * updating smart collections
25
+ * updating solr, our search server, after product changes
26
+ * batch imports
27
+ * spam checks
28
+
29
+ [Follow us on Twitter][twitter] to get updates and notices about new releases.
30
+
31
+ [twitter]: https://twitter.com/delayedjob
32
+
33
+ Installation
34
+ ============
35
+ delayed_job 3.0.0 only supports Rails 3.0+. See the [2.0
36
+ branch](https://github.com/collectiveidea/delayed_job/tree/v2.0) for Rails 2.
37
+
38
+ delayed_job supports multiple backends for storing the job queue. [See the wiki
39
+ for other backends](https://github.com/collectiveidea/delayed_job/wiki/Backends).
40
+
41
+ If you plan to use delayed_job with Active Record, add `delayed_job_active_record` to your `Gemfile`.
42
+
43
+ ```ruby
44
+ gem 'delayed_job_active_record'
45
+ ```
46
+
47
+ If you plan to use delayed_job with Mongoid, add `delayed_job_mongoid` to your `Gemfile`.
48
+
49
+ ```ruby
50
+ gem 'delayed_job_mongoid'
51
+ ```
52
+
53
+ Run `bundle install` to install the backend and delayed_job gems.
54
+
55
+ The Active Record backend requires a jobs table. You can create that table by
56
+ running the following command:
57
+
58
+ rails generate delayed_job:active_record
59
+ rake db:migrate
60
+
61
+ For Rails 4.2, see [below](#rails-42)
62
+
63
+ Development
64
+ ===========
65
+ In development mode, if you are using Rails 3.1+, your application code will automatically reload every 100 jobs or when the queue finishes.
66
+ You no longer need to restart Delayed Job every time you update your code in development.
67
+
68
+ Rails 4.2
69
+ =========
70
+ Set the queue_adapter in config/application.rb
71
+
72
+ ```ruby
73
+ config.active_job.queue_adapter = :delayed_job
74
+ ```
75
+
76
+ See the [rails guide](http://guides.rubyonrails.org/active_job_basics.html#setting-the-backend) for more details.
77
+
78
+ Rails 4
79
+ =======
80
+ If you are using the protected_attributes gem, it must appear before delayed_job in your gemfile.
81
+
82
+ Upgrading from 2.x to 3.0.0 on Active Record
83
+ ============================================
84
+ Delayed Job 3.0.0 introduces a new column to the delayed_jobs table.
85
+
86
+ If you're upgrading from Delayed Job 2.x, run the upgrade generator to create a migration to add the column.
87
+
88
+ rails generate delayed_job:upgrade
89
+ rake db:migrate
90
+
91
+ Queuing Jobs
92
+ ============
93
+ Call `.delay.method(params)` on any object and it will be processed in the background.
94
+
95
+ ```ruby
96
+ # without delayed_job
97
+ @user.activate!(@device)
98
+
99
+ # with delayed_job
100
+ @user.delay.activate!(@device)
101
+ ```
102
+
103
+ If a method should always be run in the background, you can call
104
+ `#handle_asynchronously` after the method declaration:
105
+
106
+ ```ruby
107
+ class Device
108
+ def deliver
109
+ # long running method
110
+ end
111
+ handle_asynchronously :deliver
112
+ end
113
+
114
+ device = Device.new
115
+ device.deliver
116
+ ```
117
+
118
+ handle_asynchronously can take as options anything you can pass to delay. In
119
+ addition, the values can be Proc objects allowing call time evaluation of the
120
+ value. For some examples:
121
+
122
+ ```ruby
123
+ class LongTasks
124
+ def send_mailer
125
+ # Some other code
126
+ end
127
+ handle_asynchronously :send_mailer, :priority => 20
128
+
129
+ def in_the_future
130
+ # Some other code
131
+ end
132
+ # 5.minutes.from_now will be evaluated when in_the_future is called
133
+ handle_asynchronously :in_the_future, :run_at => Proc.new { 5.minutes.from_now }
134
+
135
+ def self.when_to_run
136
+ 2.hours.from_now
137
+ end
138
+
139
+ class << self
140
+ def call_a_class_method
141
+ # Some other code
142
+ end
143
+ handle_asynchronously :call_a_class_method, :run_at => Proc.new { when_to_run }
144
+ end
145
+
146
+ attr_reader :how_important
147
+
148
+ def call_an_instance_method
149
+ # Some other code
150
+ end
151
+ handle_asynchronously :call_an_instance_method, :priority => Proc.new {|i| i.how_important }
152
+ end
153
+ ```
154
+
155
+ If you ever want to call a `handle_asynchronously`'d method without Delayed Job, for instance while debugging something at the console, just add `_without_delay` to the method name. For instance, if your original method was `foo`, then call `foo_without_delay`.
156
+
157
+ Rails 3 Mailers
158
+ ===============
159
+ Due to how mailers are implemented in Rails 3, we had to do a little work around to get delayed_job to work.
160
+
161
+ ```ruby
162
+ # without delayed_job
163
+ Notifier.signup(@user).deliver
164
+
165
+ # with delayed_job
166
+ Notifier.delay.signup(@user)
167
+
168
+ # with delayed_job running at a specific time
169
+ Notifier.delay(run_at: 5.minutes.from_now).signup(@user)
170
+ ```
171
+
172
+ Remove the `.deliver` method to make it work. It's not ideal, but it's the best
173
+ we could do for now.
174
+
175
+ Named Queues
176
+ ============
177
+ DJ 3 introduces Resque-style named queues while still retaining DJ-style
178
+ priority. The goal is to provide a system for grouping tasks to be worked by
179
+ separate pools of workers, which may be scaled and controlled individually.
180
+
181
+ Jobs can be assigned to a queue by setting the `queue` option:
182
+
183
+ ```ruby
184
+ object.delay(:queue => 'tracking').method
185
+
186
+ Delayed::Job.enqueue job, :queue => 'tracking'
187
+
188
+ handle_asynchronously :tweet_later, :queue => 'tweets'
189
+ ```
190
+
191
+ Running Jobs
192
+ ============
193
+ `script/delayed_job` can be used to manage a background process which will
194
+ start working off jobs.
195
+
196
+ To do so, add `gem "daemons"` to your `Gemfile` and make sure you've run `rails
197
+ generate delayed_job`.
198
+
199
+ You can then do the following:
200
+
201
+ RAILS_ENV=production script/delayed_job start
202
+ RAILS_ENV=production script/delayed_job stop
203
+
204
+ # Runs two workers in separate processes.
205
+ RAILS_ENV=production script/delayed_job -n 2 start
206
+ RAILS_ENV=production script/delayed_job stop
207
+
208
+ # Set the --queue or --queues option to work from a particular queue.
209
+ RAILS_ENV=production script/delayed_job --queue=tracking start
210
+ RAILS_ENV=production script/delayed_job --queues=mailers,tasks start
211
+
212
+ # Use the --pool option to specify a worker pool. You can use this option multiple times to start different numbers of workers for different queues.
213
+ # The following command will start 1 worker for the tracking queue,
214
+ # 2 workers for the mailers and tasks queues, and 2 workers for any jobs:
215
+ RAILS_ENV=production script/delayed_job --pool=tracking --pool=mailers,tasks:2 --pool=*:2 start
216
+
217
+ # Runs all available jobs and then exits
218
+ RAILS_ENV=production script/delayed_job start --exit-on-complete
219
+ # or to run in the foreground
220
+ RAILS_ENV=production script/delayed_job run --exit-on-complete
221
+
222
+ **Rails 4:** *replace script/delayed_job with bin/delayed_job*
223
+
224
+ Workers can be running on any computer, as long as they have access to the
225
+ database and their clock is in sync. Keep in mind that each worker will check
226
+ the database at least every 5 seconds.
227
+
228
+ You can also invoke `rake jobs:work` which will start working off jobs. You can
229
+ cancel the rake task with `CTRL-C`.
230
+
231
+ If you want to just run all available jobs and exit you can use `rake jobs:workoff`
232
+
233
+ Work off queues by setting the `QUEUE` or `QUEUES` environment variable.
234
+
235
+ QUEUE=tracking rake jobs:work
236
+ QUEUES=mailers,tasks rake jobs:work
237
+
238
+ Restarting delayed_job
239
+ ======================
240
+
241
+ The following syntax will restart delayed jobs:
242
+
243
+ RAILS_ENV=production script/delayed_job restart
244
+
245
+ To restart multiple delayed_job workers:
246
+
247
+ RAILS_ENV=production script/delayed_job -n2 restart
248
+
249
+ **Rails 4:** *replace script/delayed_job with bin/delayed_job*
250
+
251
+
252
+
253
+ Custom Jobs
254
+ ===========
255
+ 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.
256
+
257
+ ```ruby
258
+ NewsletterJob = Struct.new(:text, :emails) do
259
+ def perform
260
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
261
+ end
262
+ end
263
+
264
+ Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.pluck(:email))
265
+ ```
266
+
267
+ To set a per-job max attempts that overrides the Delayed::Worker.max_attempts you can define a max_attempts method on the job
268
+
269
+ ```ruby
270
+ NewsletterJob = Struct.new(:text, :emails) do
271
+ def perform
272
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
273
+ end
274
+
275
+ def max_attempts
276
+ 3
277
+ end
278
+ end
279
+ ```
280
+
281
+ To set a per-job max run time that overrides the Delayed::Worker.max_run_time you can define a max_run_time method on the job
282
+
283
+ NOTE: this can ONLY be used to set a max_run_time that is lower than Delayed::Worker.max_run_time. Otherwise the lock on the job would expire and another worker would start the working on the in progress job.
284
+
285
+ ```ruby
286
+ NewsletterJob = Struct.new(:text, :emails) do
287
+ def perform
288
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
289
+ end
290
+
291
+ def max_run_time
292
+ 120 # seconds
293
+ end
294
+ end
295
+ ```
296
+
297
+ To set a default queue name for a custom job that overrides Delayed::Worker.default_queue_name, you can define a queue_name method on the job
298
+
299
+ ```ruby
300
+ NewsletterJob = Struct.new(:text, :emails) do
301
+ def perform
302
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
303
+ end
304
+
305
+ def queue_name
306
+ 'newsletter_queue'
307
+ end
308
+ end
309
+ ```
310
+
311
+ On error, the job is scheduled again in 5 seconds + N ** 4, where N is the number of attempts. You can define your own `reschedule_at` method to override this default behavior.
312
+
313
+ ```ruby
314
+ NewsletterJob = Struct.new(:text, :emails) do
315
+ def perform
316
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
317
+ end
318
+
319
+ def reschedule_at(current_time, attempts)
320
+ current_time + 5.seconds
321
+ end
322
+ end
323
+ ```
324
+
325
+ Hooks
326
+ =====
327
+ You can define hooks on your job that will be called at different stages in the process:
328
+
329
+ ```ruby
330
+ class ParanoidNewsletterJob < NewsletterJob
331
+ def enqueue(job)
332
+ record_stat 'newsletter_job/enqueue'
333
+ end
334
+
335
+ def perform
336
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
337
+ end
338
+
339
+ def before(job)
340
+ record_stat 'newsletter_job/start'
341
+ end
342
+
343
+ def after(job)
344
+ record_stat 'newsletter_job/after'
345
+ end
346
+
347
+ def success(job)
348
+ record_stat 'newsletter_job/success'
349
+ end
350
+
351
+ def error(job, exception)
352
+ Airbrake.notify(exception)
353
+ end
354
+
355
+ def failure(job)
356
+ page_sysadmin_in_the_middle_of_the_night
357
+ end
358
+ end
359
+ ```
360
+
361
+ Gory Details
362
+ ============
363
+ The library revolves around a delayed_jobs table which looks as follows:
364
+
365
+ ```ruby
366
+ create_table :delayed_jobs, :force => true do |table|
367
+ table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
368
+ table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
369
+ table.text :handler # YAML-encoded string of the object that will do work
370
+ table.text :last_error # reason for last failure (See Note below)
371
+ table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future.
372
+ table.datetime :locked_at # Set when a client is working on this object
373
+ table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
374
+ table.string :locked_by # Who is working on this object (if locked)
375
+ table.string :queue # The name of the queue this job is in
376
+ table.timestamps
377
+ end
378
+ ```
379
+
380
+ On error, the job is scheduled again in 5 seconds + N ** 4, where N is the number of attempts or using the job's defined `reschedule_at` method.
381
+
382
+ The default `Worker.max_attempts` is 25. After this, the job either deleted (default), or left in the database with "failed_at" set.
383
+ With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours.
384
+
385
+ 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
386
+ make sure your job doesn't exceed this time. You should set this to the longest time you think the job could take.
387
+
388
+ By default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set
389
+ `Delayed::Worker.destroy_failed_jobs = false`. The failed jobs will be marked with non-null failed_at.
390
+
391
+ 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.
392
+
393
+ The default behavior is to read 5 jobs from the queue when finding an available job. You can configure this by setting `Delayed::Worker.read_ahead`.
394
+
395
+ By default all jobs will be queued without a named queue. A default named queue can be specified by using `Delayed::Worker.default_queue_name`.
396
+
397
+ It is possible to disable delayed jobs for testing purposes. Set `Delayed::Worker.delay_jobs = false` to execute all jobs realtime.
398
+
399
+ You may need to raise exceptions on SIGTERM signals, `Delayed::Worker.raise_signal_exceptions = :term` will cause the worker to raise a `SignalException` causing the running job to abort and be unlocked, which makes the job available to other workers. The default for this option is false.
400
+
401
+ Here is an example of changing job parameters in Rails:
402
+
403
+ ```ruby
404
+ # config/initializers/delayed_job_config.rb
405
+ Delayed::Worker.destroy_failed_jobs = false
406
+ Delayed::Worker.sleep_delay = 60
407
+ Delayed::Worker.max_attempts = 3
408
+ Delayed::Worker.max_run_time = 5.minutes
409
+ Delayed::Worker.read_ahead = 10
410
+ Delayed::Worker.default_queue_name = 'default'
411
+ Delayed::Worker.delay_jobs = !Rails.env.test?
412
+ Delayed::Worker.raise_signal_exceptions = :term
413
+ Delayed::Worker.logger = Logger.new(File.join(Rails.root, 'log', 'delayed_job.log'))
414
+ ```
415
+
416
+ Cleaning up
417
+ ===========
418
+ You can invoke `rake jobs:clear` to delete all jobs in the queue.
419
+
420
+ Having problems?
421
+ ================
422
+ Good places to get help are:
423
+ * [Google Groups](http://groups.google.com/group/delayed_job) where you can join our mailing list.
424
+ * [StackOverflow](http://stackoverflow.com/questions/tagged/delayed-job)