Class: Gitlab::Utils::RedisThrottle

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/utils/redis_throttle.rb

Class Method Summary collapse

Class Method Details

.execute_every(period, cache_key, skip_in_development: true) ⇒ Object, false

Executes a block of code at most once within a given time period using Redis for throttling. This is useful for scheduled tasks that should not execute too frequently.

Examples:

Execute a task at most once every hour

Gitlab::Utils::RedisThrottle.execute_every(1.hour, 'my_task:hourly_job') do
  puts "This will run once per hour"
end

Parameters:

  • period: (ActiveSupport::Duration, Integer)

    The minimum time period between executions

  • cache_key: (String)

    The key to use for Redis caching (must be unique for each distinct operation)

  • skip_in_development: (Boolean) (defaults to: true)

    If true, always executes in development environment (default: true)

  • block: (Proc)

    The code to execute if throttling conditions are met

Returns:

  • (Object, false)

    The result of the block or false if execution was throttled



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/gitlab/utils/redis_throttle.rb', line 21

def self.execute_every(period, cache_key, skip_in_development: true)
  return yield if skip_in_development && Rails.env.development?
  return yield unless period

  Gitlab::Redis::SharedState.with do |redis|
    key_set = redis.set(cache_key, 1, ex: period, nx: true)
    break false unless key_set

    yield
  end
end