efficiency20-delayed_job 1.8.51

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,184 @@
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, run:
40
+
41
+ <pre>
42
+ script/generate delayed_job
43
+ rake db:migrate
44
+ </pre>
45
+
46
+ h2. Upgrading to 1.8
47
+
48
+ If you are upgrading from a previous release, you will need to generate the new @script/delayed_job@:
49
+
50
+ <pre>
51
+ script/generate delayed_job --skip-migration
52
+ </pre>
53
+
54
+ h2. Queuing Jobs
55
+
56
+ Call @#send_later(method, params)@ on any object and it will be processed in the background.
57
+
58
+ <pre>
59
+ # without delayed_job
60
+ Notifier.deliver_signup(@user)
61
+
62
+ # with delayed_job
63
+ Notifier.send_later :deliver_signup, @user
64
+ </pre>
65
+
66
+ If a method should always be run in the background, you can call @#handle_asynchronously@ after the method declaration:
67
+
68
+ <pre>
69
+ class Device
70
+ def deliver
71
+ # long running method
72
+ end
73
+ handle_asynchronously :deliver
74
+ end
75
+
76
+ device = Device.new
77
+ device.deliver
78
+ </pre>
79
+
80
+ h2. Running Jobs
81
+
82
+ @script/delayed_job@ can be used to manage a background process which will start working off jobs.
83
+
84
+ <pre>
85
+ $ RAILS_ENV=production script/delayed_job start
86
+ $ RAILS_ENV=production script/delayed_job stop
87
+
88
+ # Runs two workers in separate processes.
89
+ $ RAILS_ENV=production script/delayed_job -n 2 start
90
+ $ RAILS_ENV=production script/delayed_job stop
91
+ </pre>
92
+
93
+ 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.
94
+
95
+ You can also invoke @rake jobs:work@ which will start working off jobs. You can cancel the rake task with @CTRL-C@.
96
+
97
+ h2. Custom Jobs
98
+
99
+ 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.
100
+
101
+ <pre>
102
+ class NewsletterJob < Struct.new(:text, :emails)
103
+ def perform
104
+ emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
105
+ end
106
+ end
107
+
108
+ Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.find(:all).collect(&:email))
109
+ </pre>
110
+
111
+ h2. Gory Details
112
+
113
+ The library evolves around a delayed_jobs table which looks as follows:
114
+
115
+ create_table :delayed_jobs, :force => true do |table|
116
+ table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
117
+ table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
118
+ table.text :handler # YAML-encoded string of the object that will do work
119
+ table.text :last_error # reason for last failure (See Note below)
120
+ table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future.
121
+ table.datetime :locked_at # Set when a client is working on this object
122
+ table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
123
+ table.string :locked_by # Who is working on this object (if locked)
124
+ table.timestamps
125
+ end
126
+
127
+ On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries.
128
+
129
+ The default Job::max_attempts is 25. After this, the job either deleted (default), or left in the database with "failed_at" set.
130
+ With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours.
131
+
132
+ The default Job::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
133
+ make sure your job doesn't exceed this time. You should set this to the longest time you think the job could take.
134
+
135
+ By default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set
136
+ Delayed::Job.destroy_failed_jobs = false. The failed jobs will be marked with non-null failed_at.
137
+
138
+ Here is an example of changing job parameters in Rails:
139
+
140
+ <pre>
141
+ # config/initializers/delayed_job_config.rb
142
+ Delayed::Job.destroy_failed_jobs = false
143
+ silence_warnings do
144
+ Delayed::Worker::sleep_delay = 60
145
+ Delayed::Job::max_attempts = 3
146
+ Delayed::Job::max_run_time = 5.minutes
147
+ end
148
+ </pre>
149
+
150
+ h3. Cleaning up
151
+
152
+ You can invoke @rake jobs:clear@ to delete all jobs in the queue.
153
+
154
+ h2. Mailing List
155
+
156
+ Join us on the mailing list at http://groups.google.com/group/delayed_job
157
+
158
+ h2. How to contribute
159
+
160
+ If you find what looks like a bug:
161
+
162
+ # Check the GitHub issue tracker to see if anyone else has had the same issue.
163
+ http://github.com/collectiveidea/delayed_job/issues/
164
+ # If you don't see anything, create an issue with information on how to reproduce it.
165
+
166
+ If you want to contribute an enhancement or a fix:
167
+
168
+ # Fork the project on github.
169
+ http://github.com/collectiveidea/delayed_job/
170
+ # Make your changes with tests.
171
+ # Commit the changes without making changes to the Rakefile, VERSION, or any other files that aren't related to your enhancement or fix
172
+ # Send a pull request.
173
+
174
+ h3. Changes
175
+
176
+ * 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.
177
+
178
+ * 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.
179
+
180
+ * 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.
181
+
182
+ * 1.2.0: Added #send_later to Object for simpler job creation
183
+
184
+ * 1.0.0: Initial release
@@ -0,0 +1,34 @@
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 = "efficiency20-delayed_job"
11
+ s.summary = "Database-backed asynchronous priority queue system -- Extracted from Shopify"
12
+ s.email = "tech@efficiency20.com"
13
+ s.homepage = "http://github.com/efficiency20/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 = ["Efficiency20", "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
+ s.add_dependency "daemons"
21
+ s.test_files = Dir['spec/**/*']
22
+ end
23
+
24
+ require 'spec/rake/spectask'
25
+
26
+ task :default => :spec
27
+
28
+ desc 'Run the specs'
29
+ Spec::Rake::SpecTask.new(:spec) do |t|
30
+ t.libs << 'lib'
31
+ t.pattern = 'spec/**/*_spec.rb'
32
+ t.verbose = true
33
+ end
34
+
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.8.51
@@ -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,70 @@
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{efficiency20-delayed_job}
8
+ s.version = "1.8.51"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["Efficiency20", "Brandon Keepers", "Tobias L\303\274tke"]
12
+ s.date = %q{2010-04-12}
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{tech@efficiency20.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
+ "efficiency20-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/command.rb",
31
+ "lib/delayed/job.rb",
32
+ "lib/delayed/message_sending.rb",
33
+ "lib/delayed/performable_method.rb",
34
+ "lib/delayed/recipes.rb",
35
+ "lib/delayed/tasks.rb",
36
+ "lib/delayed/worker.rb",
37
+ "lib/delayed_job.rb",
38
+ "recipes/delayed_job.rb",
39
+ "spec/database.rb",
40
+ "spec/delayed_method_spec.rb",
41
+ "spec/job_spec.rb",
42
+ "spec/story_spec.rb",
43
+ "tasks/jobs.rake"
44
+ ]
45
+ s.homepage = %q{http://github.com/efficiency20/delayed_job}
46
+ s.rdoc_options = ["--main", "README.textile", "--inline-source", "--line-numbers"]
47
+ s.require_paths = ["lib"]
48
+ s.rubygems_version = %q{1.3.6}
49
+ s.summary = %q{Database-backed asynchronous priority queue system -- Extracted from Shopify}
50
+ s.test_files = [
51
+ "spec/database.rb",
52
+ "spec/delayed_method_spec.rb",
53
+ "spec/job_spec.rb",
54
+ "spec/story_spec.rb"
55
+ ]
56
+
57
+ if s.respond_to? :specification_version then
58
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
59
+ s.specification_version = 3
60
+
61
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
62
+ s.add_runtime_dependency(%q<daemons>, [">= 0"])
63
+ else
64
+ s.add_dependency(%q<daemons>, [">= 0"])
65
+ end
66
+ else
67
+ s.add_dependency(%q<daemons>, [">= 0"])
68
+ end
69
+ end
70
+
@@ -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,20 @@
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
+ end
16
+
17
+ def self.down
18
+ drop_table :delayed_jobs
19
+ end
20
+ 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,103 @@
1
+ require 'rubygems'
2
+ require 'daemons'
3
+ require 'optparse'
4
+
5
+ module Delayed
6
+ class Command
7
+ attr_accessor :worker_count
8
+
9
+ def initialize(args)
10
+ @files_to_reopen = []
11
+ @options = {
12
+ :quiet => true,
13
+ :pid_dir => "#{RAILS_ROOT}/tmp/pids"
14
+ }
15
+
16
+ @worker_count = 1
17
+
18
+ opts = OptionParser.new do |opts|
19
+ opts.banner = "Usage: #{File.basename($0)} [options] start|stop|restart|run"
20
+
21
+ opts.on('-h', '--help', 'Show this message') do
22
+ puts opts
23
+ exit 1
24
+ end
25
+ opts.on('-e', '--environment=NAME', 'Specifies the environment to run this delayed jobs under (test/development/production).') do |e|
26
+ STDERR.puts "The -e/--environment option has been deprecated and has no effect. Use RAILS_ENV and see http://github.com/collectiveidea/delayed_job/issues/#issue/7"
27
+ end
28
+ opts.on('--min-priority N', 'Minimum priority of jobs to run.') do |n|
29
+ @options[:min_priority] = n
30
+ end
31
+ opts.on('--max-priority N', 'Maximum priority of jobs to run.') do |n|
32
+ @options[:max_priority] = n
33
+ end
34
+ opts.on('-n', '--number_of_workers=workers', "Number of unique workers to spawn") do |worker_count|
35
+ @worker_count = worker_count.to_i rescue 1
36
+ end
37
+ opts.on('--pid-dir=DIR', 'Specifies an alternate directory in which to store the process ids.') do |dir|
38
+ @options[:pid_dir] = dir
39
+ end
40
+ opts.on('-i', '--identifier=n', 'A numeric identifier for the worker.') do |n|
41
+ @options[:identifier] = n
42
+ end
43
+ end
44
+ @args = opts.parse!(args)
45
+ end
46
+
47
+ def daemonize
48
+
49
+ ObjectSpace.each_object(File) do |file|
50
+ @files_to_reopen << file unless file.closed?
51
+ end
52
+
53
+ dir = @options[:pid_dir]
54
+ Dir.mkdir(dir) unless File.exists?(dir)
55
+
56
+ if @worker_count > 1 && @options[:identifier]
57
+ raise ArgumentError, 'Cannot specify both --number-of-workers and --identifier'
58
+ elsif @worker_count == 1 && @options[:identifier]
59
+ process_name = "delayed_job.#{@options[:identifier]}"
60
+ run_process(process_name, dir)
61
+ else
62
+ worker_count.times do |worker_index|
63
+ process_name = worker_count == 1 ? "delayed_job" : "delayed_job.#{worker_index}"
64
+ run_process(process_name, dir)
65
+ end
66
+ end
67
+ end
68
+
69
+ def run_process(process_name, dir)
70
+ Daemons.run_proc(process_name, :dir => dir, :dir_mode => :normal, :ARGV => @args) do |*args|
71
+ run process_name
72
+ end
73
+ end
74
+
75
+ def run(worker_name = nil)
76
+ Dir.chdir(RAILS_ROOT)
77
+
78
+ # Re-open file handles
79
+ @files_to_reopen.each do |file|
80
+ begin
81
+ file.reopen file.path
82
+ file.sync = true
83
+ rescue ::Exception
84
+ end
85
+ end
86
+
87
+ Delayed::Worker.logger = Logger.new(File.join(RAILS_ROOT, 'log', 'delayed_job.log'))
88
+ if Delayed::Worker.logger.respond_to? :auto_flushing=
89
+ Delayed::Worker.logger.auto_flushing = true
90
+ end
91
+ ActiveRecord::Base.connection.reconnect!
92
+
93
+ worker = Delayed::Worker.new(@options)
94
+ worker.name_prefix = "#{worker_name} "
95
+ worker.start
96
+ rescue => e
97
+ Rails.logger.fatal e
98
+ STDERR.puts e.message
99
+ exit 1
100
+ end
101
+
102
+ end
103
+ end