-
Notifications
You must be signed in to change notification settings - Fork 0
/
window_counter.rb
49 lines (41 loc) · 1016 Bytes
/
window_counter.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
require 'thread'
module QueueStick
class WindowCounter
attr_reader :name
# Time window is in minutes.
def initialize(name, window)
raise ArgumentError,
'counter requires a name' if name.nil?
raise ArgumentError,
'counter requires a time window' if window.nil?
@name = name
@window = window
@counts = Hash.new { |h, k| h[k] = 0 }
@mutex = Mutex.new
end
def count
current_minute = self.class.current_minute
range = (current_minute - @window)..current_minute
sum = 0
@mutex.synchronize do
range.each do |key|
sum += @counts[key]
end
end
sum
end
def increment!(by = 1)
current_minute = self.class.current_minute
@mutex.synchronize do
@counts[current_minute] += by
end
end
private
def self.current_minute
minute_for(Time.now)
end
def self.minute_for(time)
(time.to_f / 60).round
end
end
end