Class: Async::Throttler
- Inherits:
-
Object
- Object
- Async::Throttler
- Defined in:
- lib/async/throttler.rb
Overview
Instance Method Summary collapse
- #async(parent: @parent, timeout: 0) ⇒ Object
-
#initialize(capacity, rate, parent: Async::Task.current) ⇒ Throttler
constructor
A new instance of Throttler.
- #wait(timeout: 0) ⇒ Object
Constructor Details
#initialize(capacity, rate, parent: Async::Task.current) ⇒ Throttler
Returns a new instance of Throttler.
5 6 7 8 9 10 11 12 13 14 15 |
# File 'lib/async/throttler.rb', line 5 def initialize(capacity, rate, parent: Async::Task.current) raise ArgumentError, "capacity must be > 0" unless capacity.positive? raise ArgumentError, "rate must be > 0" unless rate.positive? @capacity = capacity @tokens = capacity @rate = rate @parent = parent @timestamp = Time.new end |
Instance Method Details
#async(parent: @parent, timeout: 0) ⇒ Object
28 29 30 31 |
# File 'lib/async/throttler.rb', line 28 def async(parent: @parent, timeout: 0, &) wait(timeout:) parent.async(&) end |
#wait(timeout: 0) ⇒ Object
17 18 19 20 21 22 23 24 25 26 |
# File 'lib/async/throttler.rb', line 17 def wait(timeout: 0) with_timeout(timeout) do while @tokens < 1 fill! sleep(1.0 / @rate) end end @tokens -= 1 end |