Can i save changes in the value before redis key expires

I could not find better solution. I have IDs and ranks in my Redis. Is it possible for me to save the changed ranks to the database before the Redis key expires?. can I trigger some function before it expires x time earlier

You can use TTL (time to live) from redis which tell how much time left for a key to get expired and trigger a thread to save your rank in you DB:

Suppose you have a rank key whose value is 30 in redis then:

import redis
from threading import Timer

# initializing the Redis client first
r = redis.StrictRedis(host='localhost', port=6379, db=0)

# simulate saving data to the database
def save_to_database(key, value):
    print(f"Saving key: {key}, value: {value} to database")
    # replace with actual database save logic
    # Example : db.save({"key": key, "rank": value})

# function to monitor and save data
def monitor_and_save(key):
    ttl = r.ttl(key)  # get the ttime to live (TTL) of the key
    if ttl > 30:
        # schedule the save operation to run 30 seconds before expiration
        delay = ttl - 30
        print(f"Scheduling save operation for key: {key} in {delay} seconds")
        Timer(delay, lambda: save_to_database(key, r.get(key).decode())).start()
    else:
        # if TTL is less than 30 seconds save immediately
        print(f"Key: {key} is about to expire, saving immediately")
        save_to_database(key, r.get(key).decode())

# for example 
# set a key with a 60 second expiration time
r.set("rank", 3, ex=60)

# monitor and save the key
monitor_and_save("rank")
Вернуться на верх