user12119548
user12119548

Reputation:

Is there a anyway to make redis key value decrease by 1 over time?

I want to use only 1 key value pair in Redis database. and the value will be decreased by 1 in every 60 seconds. Is it possible?

Upvotes: 1

Views: 1445

Answers (1)

for_stack
for_stack

Reputation: 23031

An interesting question :) Yes, you can do that with a trick.

As we known Redis TTL can be decreased automatically over time. So you can use TTL as the value, and the TTL will decrease by 1 every second.

Say, you want to set a value of N, in order to achieve your goal, you can set a key-value pair with expiration TTL = 60 * N:

SET key N EX TTL

When you want to get the value, just get its TTL, and do some math:

ttl = TTL key

if (ttl > 0)
   value = ttl / 60 + 1
else
   // no longer exist

Upvotes: 7

Related Questions