moneypools-delayed_job 1.8.4

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1 @@
1
+ *.gem
@@ -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,195 @@
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. The default is Active Record, which requires a jobs table.
44
+
45
+ <pre>
46
+ script/generate delayed_job
47
+ rake db:migrate
48
+ </pre>
49
+
50
+ You can change the backend in an initializer:
51
+
52
+ <pre>
53
+ # config/initializers/delayed_job.rb
54
+ Delayed::Worker.backend = :mongo_mapper
55
+ </pre>
56
+
57
+ h2. Upgrading to 1.8
58
+
59
+ If you are upgrading from a previous release, you will need to generate the new @script/delayed_job@:
60
+
61
+ <pre>
62
+ script/generate delayed_job --skip-migration
63
+ </pre>
64
+
65
+ Known Issues: script/delayed_job does not work properly with anything besides the Active Record backend. That will be resolved before the next gem release.
66
+
67
+ h2. Queuing Jobs
68
+
69
+ Call @#send_later(method, params)@ on any object and it will be processed in the background.
70
+
71
+ <pre>
72
+ # without delayed_job
73
+ Notifier.deliver_signup(@user)
74
+
75
+ # with delayed_job
76
+ Notifier.send_later :deliver_signup, @user
77
+ </pre>
78
+
79
+ If a method should always be run in the background, you can call @#handle_asynchronously@ after the method declaration:
80
+
81
+ <pre>
82
+ class Device
83
+ def deliver
84
+ # long running method
85
+ end
86
+ handle_asynchronously :deliver
87
+ end
88
+
89
+ device = Device.new
90
+ device.deliver
91
+ </pre>
92
+
93
+ h2. Running Jobs
94
+
95
+ @script/delayed_job@ can be used to manage a background process which will start working off jobs.
96
+
97
+ <pre>
98
+ $ RAILS_ENV=production script/delayed_job start
99
+ $ RAILS_ENV=production script/delayed_job stop
100
+
101
+ # Runs two workers in separate processes.
102
+ $ RAILS_ENV=production script/delayed_job -n 2 start
103
+ $ RAILS_ENV=production script/delayed_job stop
104
+ </pre>
105
+
106
+ 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.
107
+
108
+ You can also invoke @rake jobs:work@ which will start working off jobs. You can cancel the rake task with @CTRL-C@.
109
+
110
+ h2. Custom Jobs
111
+
112
+ 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.
113
+
114
+ <pre>
115
+ class NewsletterJob < Struct.new(:text, :emails)
116
+ def perform
117
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
118
+ end
119
+ end
120
+
121
+ Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.find(:all).collect(&:email))
122
+ </pre>
123
+
124
+ h2. Gory Details
125
+
126
+ The library evolves around a delayed_jobs table which looks as follows:
127
+
128
+ create_table :delayed_jobs, :force => true do |table|
129
+ table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
130
+ table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
131
+ table.text :handler # YAML-encoded string of the object that will do work
132
+ table.text :last_error # reason for last failure (See Note below)
133
+ table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future.
134
+ table.datetime :locked_at # Set when a client is working on this object
135
+ table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
136
+ table.string :locked_by # Who is working on this object (if locked)
137
+ table.timestamps
138
+ end
139
+
140
+ On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries.
141
+
142
+ The default Worker.max_attempts is 25. After this, the job either deleted (default), or left in the database with "failed_at" set.
143
+ With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours.
144
+
145
+ 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
146
+ make sure your job doesn't exceed this time. You should set this to the longest time you think the job could take.
147
+
148
+ By default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set
149
+ Delayed::Worker.destroy_failed_jobs = false. The failed jobs will be marked with non-null failed_at.
150
+
151
+ Here is an example of changing job parameters in Rails:
152
+
153
+ <pre>
154
+ # config/initializers/delayed_job_config.rb
155
+ Delayed::Worker.destroy_failed_jobs = false
156
+ Delayed::Worker.sleep_delay = 60
157
+ Delayed::Worker.max_attempts = 3
158
+ Delayed::Worker.max_run_time = 5.minutes
159
+ </pre>
160
+
161
+ h3. Cleaning up
162
+
163
+ You can invoke @rake jobs:clear@ to delete all jobs in the queue.
164
+
165
+ h2. Mailing List
166
+
167
+ Join us on the mailing list at http://groups.google.com/group/delayed_job
168
+
169
+ h2. How to contribute
170
+
171
+ If you find what looks like a bug:
172
+
173
+ # Check the GitHub issue tracker to see if anyone else has had the same issue.
174
+ http://github.com/collectiveidea/delayed_job/issues/
175
+ # If you don't see anything, create an issue with information on how to reproduce it.
176
+
177
+ If you want to contribute an enhancement or a fix:
178
+
179
+ # Fork the project on github.
180
+ http://github.com/collectiveidea/delayed_job/
181
+ # Make your changes with tests.
182
+ # Commit the changes without making changes to the Rakefile, VERSION, or any other files that aren't related to your enhancement or fix
183
+ # Send a pull request.
184
+
185
+ h3. Changes
186
+
187
+ * 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.
188
+
189
+ * 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.
190
+
191
+ * 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.
192
+
193
+ * 1.2.0: Added #send_later to Object for simpler job creation
194
+
195
+ * 1.0.0: Initial release
@@ -0,0 +1,39 @@
1
+ # -*- encoding: utf-8 -*-
2
+ begin
3
+ require 'jeweler'
4
+ rescue LoadError
5
+ puts "Jeweler not available. Install it with: sudo gem install jeweler"
6
+ exit 1
7
+ end
8
+
9
+ Jeweler::Tasks.new do |s|
10
+ s.name = "moneypools-delayed_job"
11
+ s.summary = "Database-backed asynchronous priority queue system -- Extracted from Shopify"
12
+ s.email = "tobi@leetsoft.com"
13
+ s.homepage = "http://github.com/collectiveidea/delayed_job"
14
+ s.description = "Delayed_job (or DJ) encapsulates the common pattern of asynchronously executing longer tasks in the background. It is a direct extraction from Shopify where the job table is responsible for a multitude of core tasks."
15
+ s.authors = ["Brandon Keepers", "Tobias Lütke"]
16
+
17
+ s.has_rdoc = true
18
+ s.rdoc_options = ["--main", "README.textile", "--inline-source", "--line-numbers"]
19
+ s.extra_rdoc_files = ["README.textile"]
20
+
21
+ s.test_files = Dir['spec/**/*']
22
+
23
+ s.add_dependency "daemons"
24
+ s.add_development_dependency "rspec"
25
+ s.add_development_dependency "sqlite3-ruby"
26
+ end
27
+
28
+ require 'spec/rake/spectask'
29
+
30
+ task :default => :spec
31
+
32
+ desc 'Run the specs'
33
+ Spec::Rake::SpecTask.new(:spec) do |t|
34
+ t.libs << 'lib'
35
+ t.pattern = 'spec/*_spec.rb'
36
+ t.verbose = true
37
+ end
38
+ task :spec => :check_dependencies
39
+
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.8.4
@@ -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,94 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE DIRECTLY
3
+ # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
4
+ # -*- encoding: utf-8 -*-
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = %q{delayed_job}
8
+ s.version = "1.8.4"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["Brandon Keepers", "Tobias L\303\274tke"]
12
+ s.date = %q{2010-02-23}
13
+ s.description = %q{Delayed_job (or DJ) encapsulates the common pattern of asynchronously executing longer tasks in the background. It is a direct extraction from Shopify where the job table is responsible for a multitude of core tasks.}
14
+ s.email = %q{tobi@leetsoft.com}
15
+ s.extra_rdoc_files = [
16
+ "README.textile"
17
+ ]
18
+ s.files = [
19
+ ".gitignore",
20
+ "MIT-LICENSE",
21
+ "README.textile",
22
+ "Rakefile",
23
+ "VERSION",
24
+ "contrib/delayed_job.monitrc",
25
+ "delayed_job.gemspec",
26
+ "generators/delayed_job/delayed_job_generator.rb",
27
+ "generators/delayed_job/templates/migration.rb",
28
+ "generators/delayed_job/templates/script",
29
+ "init.rb",
30
+ "lib/delayed/backend/active_record.rb",
31
+ "lib/delayed/backend/base.rb",
32
+ "lib/delayed/backend/mongo_mapper.rb",
33
+ "lib/delayed/command.rb",
34
+ "lib/delayed/message_sending.rb",
35
+ "lib/delayed/performable_method.rb",
36
+ "lib/delayed/recipes.rb",
37
+ "lib/delayed/tasks.rb",
38
+ "lib/delayed/worker.rb",
39
+ "lib/delayed_job.rb",
40
+ "recipes/delayed_job.rb",
41
+ "spec/backend/active_record_job_spec.rb",
42
+ "spec/backend/mongo_mapper_job_spec.rb",
43
+ "spec/backend/shared_backend_spec.rb",
44
+ "spec/delayed_method_spec.rb",
45
+ "spec/performable_method_spec.rb",
46
+ "spec/sample_jobs.rb",
47
+ "spec/setup/active_record.rb",
48
+ "spec/setup/mongo_mapper.rb",
49
+ "spec/spec_helper.rb",
50
+ "spec/story_spec.rb",
51
+ "spec/worker_spec.rb",
52
+ "tasks/jobs.rake"
53
+ ]
54
+ s.homepage = %q{http://github.com/collectiveidea/delayed_job}
55
+ s.rdoc_options = ["--main", "README.textile", "--inline-source", "--line-numbers"]
56
+ s.require_paths = ["lib"]
57
+ s.rubygems_version = %q{1.3.6}
58
+ s.summary = %q{Database-backed asynchronous priority queue system -- Extracted from Shopify}
59
+ s.test_files = [
60
+ "spec/backend",
61
+ "spec/backend/active_record_job_spec.rb",
62
+ "spec/backend/mongo_mapper_job_spec.rb",
63
+ "spec/backend/shared_backend_spec.rb",
64
+ "spec/delayed_method_spec.rb",
65
+ "spec/performable_method_spec.rb",
66
+ "spec/sample_jobs.rb",
67
+ "spec/setup",
68
+ "spec/setup/active_record.rb",
69
+ "spec/setup/mongo_mapper.rb",
70
+ "spec/spec_helper.rb",
71
+ "spec/story_spec.rb",
72
+ "spec/worker_spec.rb"
73
+ ]
74
+
75
+ if s.respond_to? :specification_version then
76
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
77
+ s.specification_version = 3
78
+
79
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
80
+ s.add_runtime_dependency(%q<daemons>, [">= 0"])
81
+ s.add_development_dependency(%q<rspec>, [">= 0"])
82
+ s.add_development_dependency(%q<sqlite3-ruby>, [">= 0"])
83
+ else
84
+ s.add_dependency(%q<daemons>, [">= 0"])
85
+ s.add_dependency(%q<rspec>, [">= 0"])
86
+ s.add_dependency(%q<sqlite3-ruby>, [">= 0"])
87
+ end
88
+ else
89
+ s.add_dependency(%q<daemons>, [">= 0"])
90
+ s.add_dependency(%q<rspec>, [">= 0"])
91
+ s.add_dependency(%q<sqlite3-ruby>, [">= 0"])
92
+ end
93
+ end
94
+
@@ -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
+ unless options[:skip_migration]
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.dirname(__FILE__) + '/lib/delayed_job'
@@ -0,0 +1,84 @@
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
+ named_scope :ready_to_run, lambda {|worker_name, max_run_time|
27
+ {: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]}
28
+ }
29
+ named_scope :by_priority, :order => 'priority ASC, run_at ASC'
30
+
31
+ # When a worker is exiting, make sure we don't have any locked jobs.
32
+ def self.clear_locks!(worker_name)
33
+ update_all("locked_by = null, locked_at = null", ["locked_by = ?", worker_name])
34
+ end
35
+
36
+ # Find a few candidate jobs to run (in case some immediately get locked by others).
37
+ def self.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time)
38
+ scope = self.ready_to_run(worker_name, max_run_time)
39
+ scope = scope.scoped(:conditions => ['priority >= ?', Worker.min_priority]) if Worker.min_priority
40
+ scope = scope.scoped(:conditions => ['priority <= ?', Worker.max_priority]) if Worker.max_priority
41
+
42
+ ::ActiveRecord::Base.silence do
43
+ scope.by_priority.all(:limit => limit)
44
+ end
45
+ end
46
+
47
+ # Lock this job for this worker.
48
+ # Returns true if we have the lock, false otherwise.
49
+ def lock_exclusively!(max_run_time, worker)
50
+ now = self.class.db_time_now
51
+ affected_rows = if locked_by != worker
52
+ # We don't own this job so we will update the locked_by name and the locked_at
53
+ 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])
54
+ else
55
+ # We already own this job, this may happen if the job queue crashes.
56
+ # Simply resume and update the locked_at
57
+ self.class.update_all(["locked_at = ?", now], ["id = ? and locked_by = ?", id, worker])
58
+ end
59
+ if affected_rows == 1
60
+ self.locked_at = now
61
+ self.locked_by = worker
62
+ return true
63
+ else
64
+ return false
65
+ end
66
+ end
67
+
68
+ # Get the current time (GMT or local depending on DB)
69
+ # Note: This does not ping the DB to get the time, so all your clients
70
+ # must have syncronized clocks.
71
+ def self.db_time_now
72
+ if Time.zone
73
+ Time.zone.now
74
+ elsif ::ActiveRecord::Base.default_timezone == :utc
75
+ Time.now.utc
76
+ else
77
+ Time.now
78
+ end
79
+ end
80
+
81
+ end
82
+ end
83
+ end
84
+ end