Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support splay nil to disable splay behavior #13

Merged
merged 2 commits into from
Jul 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ AllCops:
SuggestExtensions: false
TargetRubyVersion: 2.7

Gemspec/DevelopmentDependencies:
Enabled: false

Layout/ParameterAlignment:
EnforcedStyle: with_fixed_indentation
Layout/CaseIndentation:
Expand Down
17 changes: 14 additions & 3 deletions lib/amigo/scheduled_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,12 @@ def logger
end

def perform(*args)
if args.empty?
splay = self.class.splay_duration
if splay.nil? || args == [true]
self._perform
elsif args.empty?
jitter = rand(0..self.class.splay_duration.to_i)
self.class.perform_in(jitter, true)
elsif args == [true]
self._perform
else
raise "ScheduledJob#perform must be called with no arguments, or [true]"
end
Expand Down Expand Up @@ -62,6 +63,16 @@ def cron(expr)
self.cron_expr = expr
end

# When the cron job is run, it is re-enqueued
# again with a random offset. This splay prevents
# the 'thundering herd' problem, where, say, may jobs
# are meant to happen at minute 0. Instead, jobs are offset.
#
# Use +nil+ to turn off this behavior and get more precise execution.
# This is mostly useful for jobs that must run very often.
#
# +duration+ must respond to +to_i+.
# @param duration [Integer,#to_i]
def splay(duration)
self.splay_duration = duration
end
Expand Down
16 changes: 16 additions & 0 deletions spec/amigo/amigo_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,22 @@ def _perform
expect(args).to eq([true] * 20)
end

it "executes immediately when splay is nil" do
calls = []
job = Class.new do
extend Amigo::ScheduledJob
cron "* * * * *"
splay nil
define_method(:_perform) do
calls << true
end
end

expect(job).to_not receive(:perform_in)
Array.new(20) { job.new.perform }
expect(calls).to eq([true] * 20)
end

it "executes its inner _perform when performed with true" do
performed = false
job = Class.new do
Expand Down