skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    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' :)


  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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search