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.
-
#call! ⇒ Object
Runs the requested code bypassing any time frequencies Useful when we have certain actions that usually need to run periodically but in some cases need to run asap.
-
#initialize(interval: tick_interval, &block) ⇒ IntervalRunner
constructor
A new instance of IntervalRunner.
-
#reset ⇒ Object
Resets the runner, so next
#callwill run the underlying code.
Constructor Details
#initialize(interval: tick_interval, &block) ⇒ IntervalRunner
Returns a new instance of IntervalRunner.
21 22 23 24 25 |
# File 'lib/karafka/helpers/interval_runner.rb', line 21 def initialize(interval: 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
28 29 30 31 32 33 34 |
# File 'lib/karafka/helpers/interval_runner.rb', line 28 def call return if monotonic_now - @last_called_at < @interval @last_called_at = monotonic_now @block.call end |
#call! ⇒ Object
Runs the requested code bypassing any time frequencies Useful when we have certain actions that usually need to run periodically but in some cases need to run asap
39 40 41 42 |
# File 'lib/karafka/helpers/interval_runner.rb', line 39 def call! @last_called_at = monotonic_now @block.call end |
#reset ⇒ Object
Resets the runner, so next #call will run the underlying code
45 46 47 |
# File 'lib/karafka/helpers/interval_runner.rb', line 45 def reset @last_called_at = monotonic_now - @interval end |