Skip to content

Instantly share code, notes, and snippets.

@ixti
Created November 18, 2023 00:46
Show Gist options
  • Save ixti/77f344ea999ee5046c3368f0cbeb00e1 to your computer and use it in GitHub Desktop.
Save ixti/77f344ea999ee5046c3368f0cbeb00e1 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require "concurrent"
module Sidekiq
module Throttled
class ExpirableSet
attr_reader :default_ttl
def initialize(default_ttl:)
@default_ttl = default_ttl.to_i
@elements = Concurrent::Map.new
end
def add(element, ttl: default_ttl)
@elements[element] = now + ttl.to_i
end
def to_a
now.then do |horizon|
@elements.each_pair.filter_map do |element, sunset|
element if horizon <= sunset
end
end
end
private
def now
::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment