Skip to content

Instantly share code, notes, and snippets.

@palerdot
Forked from zioproto/redis-delete-old-keys.py
Created February 27, 2021 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save palerdot/0cdeef0747e07b84f4c34ea646157bb2 to your computer and use it in GitHub Desktop.
Save palerdot/0cdeef0747e07b84f4c34ea646157bb2 to your computer and use it in GitHub Desktop.
Delete Redis Stale Keys
#!/usr/bin/env python
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
# To debug code on a single key you can use this instead of the for loops:
# key = r.randomkey()
# Delete all keys not accessed since 'idletime'
for key in r.scan_iter("*"):
idle = r.object("idletime", key)
# idle time is in seconds
if idle > 3600:
r.delete(key)
# Delete all keys without a TTL to expire
for key in r.scan_iter("*"):
# ttl is a type long or -1 if it is not set
if r.ttl(key) == -1:
r.delete(key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment