w3resource

Redis PTTL

Redis PTTL Command

Redis PTTL command is used to get remaining time to live of a key that has an expire set in milliseconds instead of seconds that TTL returns the amount of remaining time.

In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exists but has no associated expire.

Starting with Redis 2.8 the return value in case of error changed:

  • The command returns -2 if the key does not exist.
  • The command returns -1 if the key exists but has no associated expire.

Here are some common uses and scenarios for the "PTTL" command:

  • Cache Management: Monitor the expiration status of cached data with millisecond precision.
  • Dynamic TTL Adjustment: Adjust TTL dynamically based on business logic or user actions.
  • Session Handling: Check the session timeout remaining for active sessions.
  • Rate Limiting: Query time remaining in rate limiting scenarios for precise control.

Syntax:

PTTL KEY_NAME

Available since

2.6.0.

Return Value

Integer value TTL in milliseconds, or a negative value

Integer reply:

  • TTL in milliseconds.
  • -1, if the key does not have expiry timeout.
  • -2, if the key does not exist.

Return Value

Integer

Example - 1: Redis PTTL

First, create a key in redis and set some value in it.

Now set the expiry of the key, and after that just check the remaining expiry time.

127.0.0.1:6379[1]> SET KEY "Apple"
OK
127.0.0.1:6379[1]> EXPIRE key 10
(integer) 1
127.0.0.1:6379[1]> PTTL key
(integer) 3368

Example - 2: Redis PTTL

127.0.0.1:6379[1]> SET key "Good"
OK
127.0.0.1:6379[1]> PEXPIRE key 3000
(integer) 1
127.0.0.1:6379[1]> PTTL key
(integer) -2
127.0.0.1:6379[1]> PTTL key
(integer) -2
127.0.0.1:6379[1]> GET key
(nil)

Previous: PEXPIREAT
Next: RANDOMKEY



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/redis/redis-pttl-key.php