Skip to content

Commit 1766672

Browse files
author
thiago rodrigues colucci
committed
Delaying the metreics calculation with delayedJob. (Thiago & Joao)
1 parent dc7a32a commit 1766672

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+2509
-11
lines changed

Diff for: Rakefile

+8
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,11 @@ require 'rake/testtask'
88
require 'rake/rdoctask'
99

1010
require 'tasks/rails'
11+
12+
begin
13+
require 'delayed_job'
14+
require 'delayed/tasks'
15+
rescue LoadError
16+
STDERR.puts "Run `rake gems:install` to install delayed_job"
17+
end
18+

Diff for: app/models/project.rb

+2-4
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,10 @@ def calculate_metrics
1919
update_attribute :svn_error, error.error_message
2020
end
2121
end
22+
2223

2324
def asynchronous_calculate_metrics
24-
# pid = Kernel.fork do
25-
calculate_metrics
26-
# end
27-
# Process.detach pid
25+
Delayed::Job.enqueue CalculateMetricsJob.new(id)
2826
end
2927

3028
def download_source_code

Diff for: config/environment.rb

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
config.gem "webrat", :lib => false, :version => ">= 0.7.0"
2626
config.gem "database_cleaner", :lib => false, :version => ">= 0.5.0"
2727
config.gem "authlogic"
28+
config.gem 'delayed_job'
2829
# Only load the plugins named here, in the order given (default is alphabetical).
2930
# :all can be used as a placeholder for all plugins not explicitly named
3031
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]

Diff for: db/migrate/010_create_delayed_jobs.rb

+21
Original file line numberDiff line numberDiff line change
@@ -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

Diff for: db/schema.rb

+16-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,22 @@
99
#
1010
# It's strongly recommended to check this file into your version control system.
1111

12-
ActiveRecord::Schema.define(:version => 9) do
12+
ActiveRecord::Schema.define(:version => 10) do
13+
14+
create_table "delayed_jobs", :force => true do |t|
15+
t.integer "priority", :default => 0
16+
t.integer "attempts", :default => 0
17+
t.text "handler"
18+
t.text "last_error"
19+
t.datetime "run_at"
20+
t.datetime "locked_at"
21+
t.datetime "failed_at"
22+
t.string "locked_by"
23+
t.datetime "created_at"
24+
t.datetime "updated_at"
25+
end
26+
27+
add_index "delayed_jobs", ["priority", "run_at"], :name => "delayed_jobs_priority"
1328

1429
create_table "metrics", :force => true do |t|
1530
t.string "name"

Diff for: script/delayed_job

+5
Original file line numberDiff line numberDiff line change
@@ -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

Diff for: spec/models/project_spec.rb

+3-4
Original file line numberDiff line numberDiff line change
@@ -247,17 +247,16 @@ def valid_analizo_hash(attributes={})
247247
end
248248
end
249249

250-
it "should calculates metrics on create" do
250+
it "should order to calculate metrics on create" do
251251
require 'resources/project_mock'
252252
project_mock = ProjectMock.new valid_project_attributes
253-
project_mock.called_calculate_metrics.should be_false
254253
project_mock.save
255-
project_mock.called_calculate_metrics.should be_true
254+
project_mock.called_asynchronous_calculate_metrics
256255
end
257256

258257
it "should save in database metrics calculated" do
259258
project = Project.create valid_project_attributes
260-
259+
project.calculate_metrics
261260
Metric.find_by_project_id(project.id).should_not be_nil
262261
end
263262

Diff for: spec/resources/project_mock.rb

+7-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
class ProjectMock < Project
2-
attr_reader :called_calculate_metrics
2+
attr_reader :called_calculate_metrics, :called_asynchronous_calculate_metrics
33

44
def initialize params
55
super params
66
@called_calculate_metrics = false
7+
@called_asynchronous_calculate_metrics = false
78
end
89

910
def calculate_metrics
1011
@called_calculate_metrics = true
1112
end
12-
end
13+
14+
def asynchronous_calculate_metrics
15+
@called_asynchronous_calculate_metrics = true
16+
end
17+
end

Diff for: vendor/plugins/delayed_job/MIT-LICENSE

+20
Original file line numberDiff line numberDiff line change
@@ -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.

Diff for: vendor/plugins/delayed_job/README.textile

+206
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
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 @.delay.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.delay.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. Changelog
204+
205+
See http://wiki.github.com/collectiveidea/delayed_job/changelog for a list of changes.
206+

0 commit comments

Comments
 (0)