How to set expiration time on key in redis – Redis EXPIRE | EXPIREAT

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to set an expiration time ( timeout ) on a key, using redis EXPIRE, PEXPIRE, EXPIREAT and PEXPIREAT command.

Expiration Time in Seconds :-

To set an expiration time on key in seconds, we will use a redis EXPIRE command in redis-cli. This number of seconds represents the time to live. If number of seconds are zero or negative, key will be deleted immediately. The syntax of redis EXPIRE is as follows :-

Syntax :-

redis host:post> EXPIRE <key name> <seconds>

Output :-

1 if the timeout was set.
0 if key does not exist.

Example :-

Redis EXPIRE

Expiration Time in Milliseconds :-

To set an expiration time on key in milliseconds, we will use a command PEXPIRE in redis-cli. The syntax of redis PEXPIRE is as follows :-

Syntax :-

redis host:post> PEXPIRE <key name> <milliseconds>

Output :-

1 if the timeout was set.
0 if key does not exist.

Example :-

Redis PEXPIRE

Expiration Time in Unix Timestamp (Seconds) :-

To set an expiration time on key in Unix Timestamp, we will use a command EXPIREAT in redis-cli. A unix timestamp is an absolute time in seconds after January 1, 1970. Any timestamp defined in the past will immediately delete the key. The syntax of redis EXPIREAT is as follows :-

Syntax :-

redis host:post> EXPIREAT <key name> <unix timestamp in seconds>

Output :-

1 if the timeout was set.
0 if key does not exist.

Example :-

Redis EXPIREAT

Expiration Time in Unix Timestamp (Milliseconds) :-

To set an expiration time on key in Unix Timestamp in milliseconds, we will use a command PEXPIREAT in redis-cli. PEXPIREAT command is very similar to EXPIREAT command with difference is that, in PEXPIREAT unix timestamp is mentioned in milliseconds while in EXPIREAT unix timestamp is mentioned in seconds.

Syntax :-

redis host:post> PEXPIREAT <key name> <unix timestamp in milliseconds>

Output :-

1 if the timeout was set.
0 if key does not exist.

Example :-

Redis PEXPIREAT

References :-

  1. EXPIRE Command Docs
  2. PEXPIRE Command Docs
  3. EXPIREAT Command Docs
  4. PEXPIREAT Command Docs

That’s all for how to set expiration time on a key in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.