Created
October 29, 2014 23:11
-
-
Save sw17ch/110103a7be4ad87c726a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
commented
Oct 29, 2014
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment