class My::Limit
Public Class Methods
new(limit)
click to toggle source
# File lib/my/limit.rb, line 6 def initialize limit @check_point = limit / 10.0 # 每执行 N 次后进行一次检查,默认为次数限制的 1/10 @max_sleep_ms = 100 # 每次暂停的毫秒数 @count = 0 end
Public Instance Methods
incr(n)
click to toggle source
# File lib/my/limit.rb, line 12 def incr n @prev_time ||= Time.now @count += n if @count >= @check_point current_time = Time.now sleep_time = @max_sleep_ms - (current_time - @prev_time)*1000 if sleep_time > 0 sleep sleep_time/1000.0 @prev_time = Time.now else @prev_time = current_time end @count = 0 end end