Class: Karafka::Helpers::IntervalRunner
- Inherits:
-
Object
- Object
- Karafka::Helpers::IntervalRunner
- Includes:
- Core::Helpers::Time
- Defined in:
- lib/karafka/helpers/interval_runner.rb
Overview
Object responsible for running given code with a given interval. It won’t run given code more often than with a given interval.
This allows us to execute certain code only once in a while.
This can be used when we have code that could be invoked often due to it being in loops or other places but would only slow things down if would run with each tick.
Instance Method Summary collapse
-
#call ⇒ Object
Runs the requested code if it was not executed previously recently.
-
#initialize(interval: ::Karafka::App.config.internal.tick_interval, &block) ⇒ IntervalRunner
constructor
A new instance of IntervalRunner.
-
#reset ⇒ Object
Resets the runner, so next
#call
will run the underlying code.
Constructor Details
#initialize(interval: ::Karafka::App.config.internal.tick_interval, &block) ⇒ IntervalRunner
Returns a new instance of IntervalRunner.
18 19 20 21 22 |
# File 'lib/karafka/helpers/interval_runner.rb', line 18 def initialize(interval: ::Karafka::App.config.internal.tick_interval, &block) @block = block @interval = interval @last_called_at = monotonic_now - @interval end |
Instance Method Details
#call ⇒ Object
Runs the requested code if it was not executed previously recently
25 26 27 28 29 30 31 |
# File 'lib/karafka/helpers/interval_runner.rb', line 25 def call return if monotonic_now - @last_called_at < @interval @last_called_at = monotonic_now @block.call end |
#reset ⇒ Object
Resets the runner, so next #call
will run the underlying code
34 35 36 |
# File 'lib/karafka/helpers/interval_runner.rb', line 34 def reset @last_called_at = monotonic_now - @interval end |