emipair-delayed_job 2.0.3.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (91) hide show
  1. data/.gitignore +2 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.textile +213 -0
  4. data/Rakefile +33 -0
  5. data/VERSION +1 -0
  6. data/benchmarks.rb +33 -0
  7. data/contrib/delayed_job.monitrc +14 -0
  8. data/contrib/delayed_job_multiple.monitrc +23 -0
  9. data/emipair-delayed_job.gemspec +25 -0
  10. data/generators/delayed_job/delayed_job_generator.rb +22 -0
  11. data/generators/delayed_job/templates/migration.rb +21 -0
  12. data/generators/delayed_job/templates/script +5 -0
  13. data/init.rb +1 -0
  14. data/lib/delayed/backend/active_record.rb +90 -0
  15. data/lib/delayed/backend/base.rb +111 -0
  16. data/lib/delayed/backend/data_mapper.rb +147 -0
  17. data/lib/delayed/backend/mongo_mapper.rb +110 -0
  18. data/lib/delayed/command.rb +109 -0
  19. data/lib/delayed/message_sending.rb +22 -0
  20. data/lib/delayed/performable_method.rb +62 -0
  21. data/lib/delayed/railtie.rb +10 -0
  22. data/lib/delayed/recipes.rb +31 -0
  23. data/lib/delayed/tasks.rb +15 -0
  24. data/lib/delayed/worker.rb +214 -0
  25. data/lib/delayed_job.rb +15 -0
  26. data/lib/passive_support.rb +4 -0
  27. data/lib/passive_support/basic_object.rb +16 -0
  28. data/lib/passive_support/core_ext.rb +8 -0
  29. data/lib/passive_support/core_ext/class.rb +1 -0
  30. data/lib/passive_support/core_ext/class/attribute_accessors.rb +57 -0
  31. data/lib/passive_support/core_ext/date.rb +10 -0
  32. data/lib/passive_support/core_ext/date/behavior.rb +42 -0
  33. data/lib/passive_support/core_ext/date/calculations.rb +241 -0
  34. data/lib/passive_support/core_ext/date/conversions.rb +107 -0
  35. data/lib/passive_support/core_ext/date_time.rb +12 -0
  36. data/lib/passive_support/core_ext/date_time/calculations.rb +126 -0
  37. data/lib/passive_support/core_ext/date_time/conversions.rb +107 -0
  38. data/lib/passive_support/core_ext/enumerable.rb +120 -0
  39. data/lib/passive_support/core_ext/kernel.rb +5 -0
  40. data/lib/passive_support/core_ext/kernel/agnostics.rb +11 -0
  41. data/lib/passive_support/core_ext/kernel/daemonizing.rb +7 -0
  42. data/lib/passive_support/core_ext/kernel/debugger.rb +16 -0
  43. data/lib/passive_support/core_ext/kernel/reporting.rb +59 -0
  44. data/lib/passive_support/core_ext/kernel/requires.rb +24 -0
  45. data/lib/passive_support/core_ext/module.rb +20 -0
  46. data/lib/passive_support/core_ext/module/aliasing.rb +74 -0
  47. data/lib/passive_support/core_ext/module/attr_accessor_with_default.rb +31 -0
  48. data/lib/passive_support/core_ext/module/attr_internal.rb +32 -0
  49. data/lib/passive_support/core_ext/module/delegation.rb +135 -0
  50. data/lib/passive_support/core_ext/module/inclusion.rb +30 -0
  51. data/lib/passive_support/core_ext/module/introspection.rb +90 -0
  52. data/lib/passive_support/core_ext/module/loading.rb +23 -0
  53. data/lib/passive_support/core_ext/module/model_naming.rb +25 -0
  54. data/lib/passive_support/core_ext/module/synchronization.rb +39 -0
  55. data/lib/passive_support/core_ext/numeric.rb +9 -0
  56. data/lib/passive_support/core_ext/numeric/bytes.rb +50 -0
  57. data/lib/passive_support/core_ext/numeric/conversions.rb +19 -0
  58. data/lib/passive_support/core_ext/numeric/time.rb +81 -0
  59. data/lib/passive_support/core_ext/object.rb +6 -0
  60. data/lib/passive_support/core_ext/object/blank.rb +76 -0
  61. data/lib/passive_support/core_ext/object/conversions.rb +15 -0
  62. data/lib/passive_support/core_ext/object/extending.rb +80 -0
  63. data/lib/passive_support/core_ext/object/instance_variables.rb +74 -0
  64. data/lib/passive_support/core_ext/object/misc.rb +90 -0
  65. data/lib/passive_support/core_ext/object/singleton_class.rb +13 -0
  66. data/lib/passive_support/core_ext/string.rb +1 -0
  67. data/lib/passive_support/core_ext/string/constantize.rb +7 -0
  68. data/lib/passive_support/core_ext/time.rb +46 -0
  69. data/lib/passive_support/core_ext/time/behavior.rb +13 -0
  70. data/lib/passive_support/core_ext/time/calculations.rb +313 -0
  71. data/lib/passive_support/core_ext/time/conversions.rb +90 -0
  72. data/lib/passive_support/core_ext/time/zones.rb +86 -0
  73. data/lib/passive_support/duration.rb +100 -0
  74. data/lib/passive_support/ordered_hash.rb +158 -0
  75. data/rails/init.rb +5 -0
  76. data/recipes/delayed_job.rb +1 -0
  77. data/spec/backend/active_record_job_spec.rb +46 -0
  78. data/spec/backend/data_mapper_job_spec.rb +16 -0
  79. data/spec/backend/mongo_mapper_job_spec.rb +94 -0
  80. data/spec/backend/shared_backend_spec.rb +268 -0
  81. data/spec/delayed_method_spec.rb +58 -0
  82. data/spec/performable_method_spec.rb +42 -0
  83. data/spec/sample_jobs.rb +25 -0
  84. data/spec/setup/active_record.rb +33 -0
  85. data/spec/setup/data_mapper.rb +24 -0
  86. data/spec/setup/mongo_mapper.rb +17 -0
  87. data/spec/spec_helper.rb +19 -0
  88. data/spec/story_spec.rb +17 -0
  89. data/spec/worker_spec.rb +225 -0
  90. data/tasks/jobs.rake +1 -0
  91. metadata +323 -0
@@ -0,0 +1,2 @@
1
+ *.gem
2
+ *.swp
@@ -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,213 @@
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
+ To install as a gem, add the following to @config/environment.rb@:
18
+
19
+ <pre>
20
+ config.gem 'delayed_job'
21
+ </pre>
22
+
23
+ Rake tasks are not automatically loaded from gems, so you'll need to add the following to your Rakefile:
24
+
25
+ <pre>
26
+ begin
27
+ require 'delayed/tasks'
28
+ rescue LoadError
29
+ STDERR.puts "Run `rake gems:install` to install delayed_job"
30
+ end
31
+ </pre>
32
+
33
+ To install as a plugin:
34
+
35
+ <pre>
36
+ script/plugin install git://github.com/collectiveidea/delayed_job.git
37
+ </pre>
38
+
39
+ After delayed_job is installed, you will need to setup the backend.
40
+
41
+ h2. Backends
42
+
43
+ delayed_job supports multiple backends for storing the job queue. There are currently implementations for Active Record, MongoMapper, and DataMapper.
44
+
45
+ h3. Active Record
46
+
47
+ The default is Active Record, which requires a jobs table.
48
+
49
+ <pre>
50
+ $ script/generate delayed_job
51
+ $ rake db:migrate
52
+ </pre>
53
+
54
+ h3. MongoMapper
55
+
56
+ <pre>
57
+ # config/initializers/delayed_job.rb
58
+ Delayed::Worker.backend = :mongo_mapper
59
+ </pre>
60
+
61
+ h3. DataMapper
62
+
63
+ <pre>
64
+ # config/initializers/delayed_job.rb
65
+ Delayed::Worker.backend = :data_mapper
66
+ Delayed::Worker.backend.auto_upgrade!
67
+ </pre>
68
+
69
+ h2. Queuing Jobs
70
+
71
+ Call @#send_later(method, params)@ on any object and it will be processed in the background.
72
+
73
+ <pre>
74
+ # without delayed_job
75
+ Notifier.deliver_signup(@user)
76
+
77
+ # with delayed_job
78
+ Notifier.send_later :deliver_signup, @user
79
+ </pre>
80
+
81
+ If a method should always be run in the background, you can call @#handle_asynchronously@ after the method declaration:
82
+
83
+ <pre>
84
+ class Device
85
+ def deliver
86
+ # long running method
87
+ end
88
+ handle_asynchronously :deliver
89
+ end
90
+
91
+ device = Device.new
92
+ device.deliver
93
+ </pre>
94
+
95
+ h2. Running Jobs
96
+
97
+ @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`.
98
+
99
+ <pre>
100
+ $ RAILS_ENV=production script/delayed_job start
101
+ $ RAILS_ENV=production script/delayed_job stop
102
+
103
+ # Runs two workers in separate processes.
104
+ $ RAILS_ENV=production script/delayed_job -n 2 start
105
+ $ RAILS_ENV=production script/delayed_job stop
106
+ </pre>
107
+
108
+ 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.
109
+
110
+ You can also invoke @rake jobs:work@ which will start working off jobs. You can cancel the rake task with @CTRL-C@.
111
+
112
+ h2. Custom Jobs
113
+
114
+ 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.
115
+
116
+ <pre>
117
+ class NewsletterJob < Struct.new(:text, :emails)
118
+ def perform
119
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
120
+ end
121
+ end
122
+
123
+ Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.find(:all).collect(&:email))
124
+ </pre>
125
+
126
+ You can also add an optional on_permanent_failure method which will run if the job has failed too many times to be retried:
127
+
128
+ <pre>
129
+ class ParanoidNewsletterJob < NewsletterJob
130
+ def perform
131
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
132
+ end
133
+
134
+ def on_permanent_failure
135
+ page_sysadmin_in_the_middle_of_the_night
136
+ end
137
+ end
138
+ </pre>
139
+
140
+ h2. Gory Details
141
+
142
+ The library evolves around a delayed_jobs table which looks as follows:
143
+
144
+ <pre>
145
+ create_table :delayed_jobs, :force => true do |table|
146
+ table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
147
+ table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
148
+ table.text :handler # YAML-encoded string of the object that will do work
149
+ table.text :last_error # reason for last failure (See Note below)
150
+ table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future.
151
+ table.datetime :locked_at # Set when a client is working on this object
152
+ table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
153
+ table.string :locked_by # Who is working on this object (if locked)
154
+ table.timestamps
155
+ end
156
+ </pre>
157
+
158
+ On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries.
159
+
160
+ The default Worker.max_attempts is 25. After this, the job either deleted (default), or left in the database with "failed_at" set.
161
+ With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours.
162
+
163
+ 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
164
+ make sure your job doesn't exceed this time. You should set this to the longest time you think the job could take.
165
+
166
+ By default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set
167
+ Delayed::Worker.destroy_failed_jobs = false. The failed jobs will be marked with non-null failed_at.
168
+
169
+ Here is an example of changing job parameters in Rails:
170
+
171
+ <pre>
172
+ # config/initializers/delayed_job_config.rb
173
+ Delayed::Worker.destroy_failed_jobs = false
174
+ Delayed::Worker.sleep_delay = 60
175
+ Delayed::Worker.max_attempts = 3
176
+ Delayed::Worker.max_run_time = 5.minutes
177
+ </pre>
178
+
179
+ h3. Cleaning up
180
+
181
+ You can invoke @rake jobs:clear@ to delete all jobs in the queue.
182
+
183
+ h2. Mailing List
184
+
185
+ Join us on the mailing list at http://groups.google.com/group/delayed_job
186
+
187
+ h2. How to contribute
188
+
189
+ If you find what looks like a bug:
190
+
191
+ # Check the GitHub issue tracker to see if anyone else has had the same issue.
192
+ http://github.com/collectiveidea/delayed_job/issues/
193
+ # If you don't see anything, create an issue with information on how to reproduce it.
194
+
195
+ If you want to contribute an enhancement or a fix:
196
+
197
+ # Fork the project on github.
198
+ http://github.com/collectiveidea/delayed_job/
199
+ # Make your changes with tests.
200
+ # Commit the changes without making changes to the Rakefile, VERSION, or any other files that aren't related to your enhancement or fix
201
+ # Send a pull request.
202
+
203
+ h3. Changes
204
+
205
+ * 1.7.0: Added failed_at column which can optionally be set after a certain amount of failed job attempts. By default failed job attempts are destroyed after about a month.
206
+
207
+ * 1.6.0: Renamed locked_until to locked_at. We now store when we start a given job instead of how long it will be locked by the worker. This allows us to get a reading on how long a job took to execute.
208
+
209
+ * 1.5.0: Job runners can now be run in parallel. Two new database columns are needed: locked_until and locked_by. This allows us to use pessimistic locking instead of relying on row level locks. This enables us to run as many worker processes as we need to speed up queue processing.
210
+
211
+ * 1.2.0: Added #send_later to Object for simpler job creation
212
+
213
+ * 1.0.0: Initial release
@@ -0,0 +1,33 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require 'rubygems'
3
+ require 'bundler'
4
+ Bundler::GemHelper.install_tasks
5
+
6
+ require 'rubygems'
7
+ require 'spec/rake/spectask'
8
+
9
+ $:.unshift(File.expand_path(File.join(File.dirname(__FILE__), 'lib')))
10
+
11
+ desc 'Default: run spec examples'
12
+ task :default => 'test'
13
+ task :test => ['test:unit', 'test:integration']
14
+
15
+ namespace :test do
16
+
17
+ desc "desc Run the unit tests"
18
+ Spec::Rake::SpecTask.new(:unit) do |t|
19
+ t.libs << 'lib'
20
+ t.pattern = 'spec/*_spec.rb'
21
+ end
22
+
23
+ [:integration, :migration].each do |name_sym|
24
+ desc "desc Run the #{name_sym} tests"
25
+ task name_sym do |t|
26
+ puts "DJ is no-op'ing test:#{name_sym}"
27
+ end
28
+ end
29
+ end
30
+
31
+ Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), 'lib', 'tasks', '**', '*.rake'))) do |file|
32
+ load file
33
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 2.0.3
@@ -0,0 +1,33 @@
1
+ $:.unshift(File.dirname(__FILE__) + '/lib')
2
+ require 'rubygems'
3
+ require 'logger'
4
+ require 'delayed_job'
5
+ require 'benchmark'
6
+
7
+ RAILS_ENV = 'test'
8
+
9
+ Delayed::Worker.logger = Logger.new('/dev/null')
10
+
11
+ BACKENDS = []
12
+ Dir.glob("#{File.dirname(__FILE__)}/spec/setup/*.rb") do |backend|
13
+ begin
14
+ backend = File.basename(backend, '.rb')
15
+ require "spec/setup/#{backend}"
16
+ BACKENDS << backend.to_sym
17
+ rescue LoadError
18
+ puts "Unable to load #{backend} backend! #{$!}"
19
+ end
20
+ end
21
+
22
+
23
+ Benchmark.bm(10) do |x|
24
+ BACKENDS.each do |backend|
25
+ require "spec/setup/#{backend}"
26
+ Delayed::Worker.backend = backend
27
+
28
+ n = 10000
29
+ n.times { "foo".send_later :length }
30
+
31
+ x.report(backend.to_s) { Delayed::Worker.new(:quiet => true).work_off(n) }
32
+ end
33
+ end
@@ -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,25 @@
1
+ Gem::Specification.new do |s|
2
+ s.name = "emipair-delayed_job"
3
+ s.version = "2.0.3.1"
4
+ s.platform = Gem::Platform::RUBY
5
+ s.authors = ["EMI"]
6
+ s.email = ["platform-ops@emimusic.com"]
7
+ s.homepage = ""
8
+ s.summary = %q{DelayedJob Merb port}
9
+ s.description = %q{DelayedJob for use form within a Merb application}
10
+
11
+ s.files = `git ls-files`.split("\n")
12
+ s.test_files = `git ls-files -- spec/*`.split("\n")
13
+ s.require_paths = ["lib"]
14
+ s.add_runtime_dependency(%q<daemons>, [">= 0"])
15
+ s.add_runtime_dependency(%q<blankslate>, [">= 0"])
16
+ s.add_development_dependency(%q<rspec>, [">= 0"])
17
+ s.add_development_dependency(%q<sqlite3-ruby>, [">= 0"])
18
+ s.add_development_dependency(%q<mongo_mapper>, [">= 0"])
19
+ s.add_development_dependency(%q<dm-core>, [">= 0"])
20
+ s.add_development_dependency(%q<dm-observer>, [">= 0"])
21
+ s.add_development_dependency(%q<dm-aggregates>, [">= 0"])
22
+ s.add_development_dependency(%q<dm-validations>, [">= 0"])
23
+ s.add_development_dependency(%q<do_sqlite3>, [">= 0"])
24
+ s.add_development_dependency(%q<database_cleaner>, [">= 0"])
25
+ end
@@ -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
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require File.join(File.dirname(__FILE__), 'rails', 'init')
@@ -0,0 +1,90 @@
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
+ return true
69
+ else
70
+ return false
71
+ end
72
+ end
73
+
74
+ # Get the current time (GMT or local depending on DB)
75
+ # Note: This does not ping the DB to get the time, so all your clients
76
+ # must have syncronized clocks.
77
+ def self.db_time_now
78
+ if Time.zone
79
+ Time.zone.now
80
+ elsif ::ActiveRecord::Base.default_timezone == :utc
81
+ Time.now.utc
82
+ else
83
+ Time.now
84
+ end
85
+ end
86
+
87
+ end
88
+ end
89
+ end
90
+ end