1

I had a issue with redis recently. I set a key using redis.setex , then I want to print something after the key is expired. I mean :

redis.setex('Hi',2,'Hello')
if redis.ttl <= 0:
    print('done') 

but it won't work. can't work with sleep or loops because the program has other parts to run ( it's a telegram bot ). i would be thankful if someone help me with that. sorry for bad English

rezamnk
  • 31
  • 1
  • 6
  • Does this answer your question? [Notification of key expiration in redis python](https://stackoverflow.com/questions/23964548/notification-of-key-expiration-in-redis-python) – sushanth Jun 09 '20 at 18:06

2 Answers2

2

Option 1: Check if the key exists

If a key has expired the key is not in the database anymore. This means, I know this is obvious, that if the key is here it has not expired ;)

So you can either run the command EXISTS or retrieve the key.

Option 2: Use Key Space Notifications

what you can do is, you can have the database publishing an event when a key is expired/deleted. I invite you to look at this part of the documentation: * KeySpace Notifications

So once the event occurs, Redis publishes an event on a channel, you can then use your Python and Subscribe to this

Option 3: Use Redis Gears & Key Spaces Notifications

The Redis community has a new module "Redis Gears" that could help you too. It is very similar to the options 2, the big differences are:

  • the way you listen to the key events gb.register(prefix='*', eventTypes=['expired'])
  • you can push the event to Redis Streams, publish an event or even process it in Python.

I hope I am helping you and you will find one of these options useful for your application

Tug Grall
  • 3,410
  • 1
  • 14
  • 16
1

well I didn't use those options but I found threading Timer! used :

def something():
    .... #call another function to run
threading.Timer(redis.ttl(key),something).start()

and the problem solved. idk if the program is optimized or not but 'When it is running properly, don't touch it' :)

rezamnk
  • 31
  • 1
  • 6