Skip to main content

Description

Set a timeout on a key. After the timeout has expired, the key will automatically be deleted.

Method Signature

Parameters

key
string
required
The key to set expiration on
seconds
number
required
The number of seconds until the key expires
option
ExpireOption
Optional modifier for the expiration behavior:
  • "NX" - Set expiry only when the key has no expiry
  • "XX" - Set expiry only when the key has an existing expiry
  • "GT" - Set expiry only when the new expiry is greater than current one
  • "LT" - Set expiry only when the new expiry is less than current one
Case-insensitive (can use lowercase: "nx", "xx", "gt", "lt")

Return Value

result
0 | 1
  • 1 if the timeout was set
  • 0 if the timeout was not set (key doesn’t exist or condition not met)

Examples

Basic expiration

Set expiry only if key has no expiry (NX)

Set expiry only if new expiry is greater (GT)

Non-existent key

See Also

  • ttl - Get the time to live for a key
  • persist - Remove the expiration from a key