Skip to content

Commit

Permalink
Job payloads may implement #max_attempts to control how many times th…
Browse files Browse the repository at this point in the history
…ey are retried
  • Loading branch information
betamatt committed Dec 1, 2010
1 parent ac22519 commit ed81e06
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 2 deletions.
4 changes: 4 additions & 0 deletions lib/delayed/backend/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ def reschedule_at
payload_object.reschedule_at(self.class.db_time_now, attempts) :
self.class.db_time_now + (attempts ** 4) + 5
end

def max_attempts
payload_object.max_attempts if payload_object.respond_to?(:max_attempts)
end

private

Expand Down
6 changes: 5 additions & 1 deletion lib/delayed/worker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def run(job)
# Reschedule the job in the future (when a job fails).
# Uses an exponential scale depending on the number of failed attempts.
def reschedule(job, time = nil)
if (job.attempts += 1) < self.class.max_attempts
if (job.attempts += 1) < max_attempts(job)
job.run_at = time || job.reschedule_at
job.unlock
job.save!
Expand All @@ -154,6 +154,10 @@ def say(text, level = Logger::INFO)
logger.add level, "#{Time.now.strftime('%FT%T%z')}: #{text}" if logger
end

def max_attempts(job)
job.max_attempts || self.class.max_attempts
end

protected

def handle_failed_job(job, error)
Expand Down
15 changes: 15 additions & 0 deletions spec/backend/shared_backend_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -299,4 +299,19 @@ def create_job(opts = {})
@job.id.should_not be_nil
end
end

context "max_attempts" do
before(:each) do
@job = described_class.enqueue SimpleJob.new
end

it 'should not be defined' do
@job.max_attempts.should be_nil
end

it 'should use the max_retries value on the payload when defined' do
@job.payload_object.stub!(:max_attempts).and_return(99)
@job.max_attempts.should == 99
end
end
end
1 change: 1 addition & 0 deletions spec/sample_jobs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def perform; sleep 250; end
class OnPermanentFailureJob < SimpleJob
def on_permanent_failure
end
def max_attempts; 1; end
end

module M
Expand Down
2 changes: 1 addition & 1 deletion spec/worker_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def job_create(opts = {})

it "should run that hook" do
@job.payload_object.should_receive :on_permanent_failure
Delayed::Worker.max_attempts.times { @worker.reschedule(@job) }
@worker.reschedule(@job)
end
end

Expand Down

0 comments on commit ed81e06

Please sign in to comment.