Class: Karafka::Helpers::IntervalRunner

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(interval: ::Karafka::App.config.internal.tick_interval, &block) ⇒ IntervalRunner

Returns a new instance of IntervalRunner.

Parameters:

  • interval (Integer) (defaults to: ::Karafka::App.config.internal.tick_interval)

    interval in ms for running the provided code. Defaults to the internal.tick_interval value

  • block (Proc)

    block of code we want to run once in a while



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

#callObject

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

#resetObject

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