EXPIRE
Sets a timeout on a key. After the timeout expires, the key is automatically deleted.
Syntax
EXPIRE key secondsDescription
The EXPIRE command sets a timeout (in seconds) on a key. Once the timeout expires, the key is automatically deleted. The timeout is set from the current time, so if you set a timeout of 60 seconds, the key will expire 60 seconds from now.
Arguments
key(required): The name of the key to set expiration on.seconds(required): The timeout in seconds. Must be a positive integer.
Return Value
Returns an Integer:
1if the timeout was set successfully0if the key doesn't exist
Examples
Setting Expiration
SET mykey "value"
EXPIRE mykey 60Response:
OK
(integer) 1Checking TTL
SET mykey "value"
EXPIRE mykey 3600
TTL mykeyResponse:
OK
(integer) 1
(integer) 3600Expiring Non-Existent Key
EXPIRE nonexistent 60Response:
(integer) 0Key Expires Automatically
SET mykey "value"
EXPIRE mykey 1
# Wait 1 second
GET mykeyResponse:
OK
(integer) 1
(nil)Notes
- The timeout is set from the current time
- Keys expire automatically - no manual cleanup needed
- Works with both string and list keys
- Returns
0if the key doesn't exist - The timeout is specified in seconds
Use Cases
- Session Management: Set expiration on session keys
- Cache Invalidation: Automatically expire cached data
- Temporary Data: Store data that should be automatically cleaned up
- Rate Limiting: Use with counters that should reset after a period