Class: Sidekiq::Bouncer

Inherits:
Object
  • Object
show all
Defined in:
lib/sidekiq/bouncer.rb,
lib/sidekiq/bouncer/config.rb,
lib/sidekiq/bouncer/version.rb

Constant Summary collapse

BUFFER =

Second.

1
DEFAULT_DELAY =

Seconds.

60
VERSION =
'0.1.1'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, delay = DEFAULT_DELAY) ⇒ Bouncer

Returns a new instance of Bouncer.



19
20
21
22
# File 'lib/sidekiq/bouncer.rb', line 19

def initialize(klass, delay = DEFAULT_DELAY)
  @klass = klass
  @delay = delay
end

Class Method Details

.configObject



10
11
12
# File 'lib/sidekiq/bouncer.rb', line 10

def config
  @config ||= Config.new
end

.configure {|config| ... } ⇒ Object

Yields:



14
15
16
# File 'lib/sidekiq/bouncer.rb', line 14

def configure(&block)
  yield config
end

Instance Method Details

#debounce(*params) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/sidekiq/bouncer.rb', line 24

def debounce(*params)
  # Refresh the timestamp in redis with debounce delay added.
  self.class.config.redis.set(key(params), now + @delay)

  # Schedule the job with not only debounce delay added, but also BUFFER.
  # BUFFER helps prevent race condition between this line and the one above.
  @klass.perform_at(now + @delay + BUFFER, *params)
end

#let_in?(*params) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/sidekiq/bouncer.rb', line 33

def let_in?(*params)
  # Only the last job should come after the timestamp.
  timestamp = self.class.config.redis.get(key(params))
  return false if Time.now.to_i < timestamp.to_i

  # But because of BUFFER, there could be mulitple last jobs enqueued within
  # the span of BUFFER. The first one will clear the timestamp, and the rest
  # will skip when they see that the timestamp is gone.
  return false if timestamp.nil?
  self.class.config.redis.del(key(params))

  true
end