0
0
Redisquery~5 mins

EXPIRE and TTL for time-to-live in Redis

Choose your learning style9 modes available
Introduction
EXPIRE and TTL help you control how long data stays in Redis before it is automatically removed. This keeps your database clean and saves space.
You want a temporary login session that expires after 30 minutes.
You store cache data that should refresh every hour.
You keep a countdown for a limited-time offer in an online store.
You want to automatically delete old notifications after a day.
You track temporary tokens that should not last forever.
Syntax
Redis
EXPIRE key seconds
TTL key
EXPIRE sets the time in seconds for a key to live before deletion.
TTL shows how many seconds remain before the key expires. Returns -1 if no expiration is set.
Examples
Sets the key 'session123' to expire in 1800 seconds (30 minutes).
Redis
EXPIRE session123 1800
Returns how many seconds remain before 'session123' expires.
Redis
TTL session123
Makes 'tempKey' expire after 60 seconds.
Redis
EXPIRE tempKey 60
Shows remaining time to live for 'tempKey'.
Redis
TTL tempKey
Sample Program
This sets a key 'mykey' with value 'hello', makes it expire in 10 seconds, then checks how many seconds remain.
Redis
SET mykey "hello"
EXPIRE mykey 10
TTL mykey
OutputSuccess
Important Notes
If you set EXPIRE on a key that does not exist, Redis returns 0 and does nothing.
TTL returns -2 if the key does not exist.
You can remove expiration with the PERSIST command.
Summary
EXPIRE sets a countdown for a key to be deleted automatically.
TTL shows how much time is left before the key expires.
These commands help manage temporary data easily.