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: tick_interval, &block) ⇒ IntervalRunner

Returns a new instance of IntervalRunner.

Parameters:

  • interval (Integer) (defaults to: 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



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

#callObject

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

#resetObject

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