Skip to content

Instantly share code, notes, and snippets.

@KarateJB
Forked from DazWorrall/foo.rb
Created October 26, 2022 11:40
Show Gist options
  • Save KarateJB/34b6834ce8aa44aac30142f2ccf619aa to your computer and use it in GitHub Desktop.
Save KarateJB/34b6834ce8aa44aac30142f2ccf619aa to your computer and use it in GitHub Desktop.
Redis sorted sets with timestamps for scores
require 'redis'
require 'active_support/time'
redis = Redis.new
# members are added with a score that is a timestamp of when they should expire
redis.zadd('test-sset', 10.minutes.from_now.to_i, 'app1')
# let's add one in the past so we can test some more
redis.zadd('test-sset', 10.minutes.ago.to_i, 'app2')
puts 'all apps'
puts redis.zrange('test-sset', 0, -1) # app1, app2
puts 'active apps'
puts redis.zrangebyscore('test-sset', Time.now.utc.to_i, '+inf') #app1
puts 'expiring old apps'
puts redis.zremrangebyscore('test-sset', '-inf', Time.now.utc.to_i) # returns # of expired elements
puts 'all remaining apps'
puts redis.zrange('test-sset', 0, -1) # app1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment