Skip to content

Instantly share code, notes, and snippets.

@sw17ch
Created October 29, 2014 23:11
Show Gist options
  • Select an option

  • Save sw17ch/110103a7be4ad87c726a to your computer and use it in GitHub Desktop.

Select an option

Save sw17ch/110103a7be4ad87c726a to your computer and use it in GitHub Desktop.
class IntervalSquelch
# Accepts an `interval` in fractional seconds and a `max_runs` as an integer.
# Will ensure that `go` calls its block no more than `max_runs` times per
# `interval`.
#
# By default, `max_runs` is 1.
def initialize(interval, max_runs = 1)
@max_runs = max_runs.to_i
@interval = interval.to_f
@tick = 0
@runs = 0
@start = Time.now.to_f
end
# `blk` will only be called if the number of times it's been called in this
# interval does not exceed the maximum number of calls per interval.
#
# Returns `true` when the block was run; otherwise, returns `false`.
def go(&blk)
tick = ((Time.now.to_f - @start) / @interval).to_i
if @tick != tick
@tick = tick
@runs = 0
end
unless @runs >= @max_runs
blk.call()
@runs += 1
true
else
false
end
end
end
count = 0
start = Time.now.to_f
s = IntervalSquelch.new(0.5, 5)
loop do
s.go do
puts "Hello World :: %03d :: %0.05f" % [count, Time.now.to_f - start]
count += 1
end
end
@sw17ch

sw17ch commented Oct 29, 2014

Copy link
Copy Markdown
Author
$ruby interval_squelch.rb
Hello World :: 000 :: 0.00002
Hello World :: 001 :: 0.00005
Hello World :: 002 :: 0.00006
Hello World :: 003 :: 0.00007
Hello World :: 004 :: 0.00007
Hello World :: 005 :: 0.50002
Hello World :: 006 :: 0.50005
Hello World :: 007 :: 0.50006
Hello World :: 008 :: 0.50007
Hello World :: 009 :: 0.50007
Hello World :: 010 :: 1.00002
Hello World :: 011 :: 1.00006
Hello World :: 012 :: 1.00007
Hello World :: 013 :: 1.00008
Hello World :: 014 :: 1.00008

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment