Class: Karafka::TimeTrackers::Poll

Inherits:
Base
  • Object
show all
Defined in:
lib/karafka/time_trackers/poll.rb

Overview

Object used to keep track of time we’ve used running certain operations. Polling is running in a single thread, thus we do not have to worry about this being thread-safe.

Examples:

Keep track of sleeping and stop after 3 seconds of 0.1 sleep intervals

time_poll = Poll.new(3000)
time_poll.start

until time_poll.exceeded?
  time_poll.start
  puts "I have #{time_poll.remaining.to_i}ms remaining to sleep..."
  sleep(0.1)
  time_poll.checkpoint
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(total_time) ⇒ TimeTracker

Returns time poll instance.

Parameters:

  • total_time (Integer)

    amount of milliseconds before we exceed the given time limit



23
24
25
26
27
# File 'lib/karafka/time_trackers/poll.rb', line 23

def initialize(total_time)
  @remaining = total_time
  @attempts = 0
  super()
end

Instance Attribute Details

#attemptsObject (readonly)

Returns the value of attribute attempts.



19
20
21
# File 'lib/karafka/time_trackers/poll.rb', line 19

def attempts
  @attempts
end

#remainingObject (readonly)

Returns the value of attribute remaining.



19
20
21
# File 'lib/karafka/time_trackers/poll.rb', line 19

def remaining
  @remaining
end

Instance Method Details

#backoffObject

Sleeps for amount of time matching attempt, so we sleep more with each attempt in case of

a retry.


53
54
55
56
57
58
59
# File 'lib/karafka/time_trackers/poll.rb', line 53

def backoff
  # backoff should not be included in the remaining time computation, otherwise it runs
  # shortly, never back-offing beyond a small number because of the sleep
  @remaining += backoff_interval
  # Sleep requires seconds not ms
  sleep(backoff_interval / 1_000.0)
end

#checkpointObject

Stops time tracking of a given piece of code and updates the remaining time.



41
42
43
# File 'lib/karafka/time_trackers/poll.rb', line 41

def checkpoint
  @remaining -= (monotonic_now - @started_at)
end

#exceeded?Boolean

Returns did we exceed the time limit.

Returns:

  • (Boolean)

    did we exceed the time limit



30
31
32
# File 'lib/karafka/time_trackers/poll.rb', line 30

def exceeded?
  @remaining <= 0
end

#retryable?Boolean

Returns If anything went wrong, can we retry after a backoff period or not (do we have enough time).

Returns:

  • (Boolean)

    If anything went wrong, can we retry after a backoff period or not (do we have enough time)



47
48
49
# File 'lib/karafka/time_trackers/poll.rb', line 47

def retryable?
  remaining > backoff_interval
end

#startObject

Starts time tracking.



35
36
37
38
# File 'lib/karafka/time_trackers/poll.rb', line 35

def start
  @attempts += 1
  @started_at = monotonic_now
end