Redis - How to expire key daily
Asked Answered
S

4

38

I know that EXPIREAT in Redis is used to specify when a key will expire. My problem though is that it takes an absolute UNIX timestamp. I'm finding a hard time thinking about what I should set as an argument if I want the key to expire at the end of the day.

This is how I set my key:

client.set(key, body);

So to set the expire at:

client.expireat(key, ???);

Any ideas? I'm using this with nodejs and sailsjs Thanks!

Sanatory answered 1/6, 2015 at 4:17 Comment(1)
which redis npm module you are using ,is that all redis npm module support expireat() function. ?Arlaarlan
C
53

If you want to expire it 24 hrs later

client.expireat(key, parseInt((+new Date)/1000) + 86400);

Or if you want it to expire exactly at the end of today, you can use .setHours on a new Date() object to get the time at the end of the day, and use that.

var todayEnd = new Date().setHours(23, 59, 59, 999);
client.expireat(key, parseInt(todayEnd/1000));
Color answered 1/6, 2015 at 4:42 Comment(7)
where is it documented?Ligature
I did not manage to find this anywhere documented? How did you find this?Thermosphere
Is expiresat sync or async? I have a lot of questionsThermosphere
@Color is the + sign in front of new Date really required?Hatband
How to set expiration never in redis ?Crankshaft
How about Date.now() instead of +new Date/1000?Garris
Here is the Node Docs: redis.js.org/#node-redis-usage-redis-commandsTimisoara
T
36

Since SETNX, SETEX, PSETEX are going to be deprecated in the next releases, the correct way is:

client.set(key, value, 'EX', 60 * 60 * 24, callback);

See here for a detailed discussion on the above.

Tartarus answered 28/2, 2017 at 9:46 Comment(0)
D
31

For new version ^4.6.7, you have can use set and expire like

await client.set(key , value, {EX: 60*60*24})

EX should be set in seconds (eg: 60 * 60 * 24 seconds = 1 day)

Delouse answered 9/4, 2023 at 5:35 Comment(3)
This is the correct way at least for versions ^4.6.7Tannenberg
yes, also for me this worked but the other options did notBerber
This is the one that works for the latest version of redis-npm. Docs: redis.js.org/#node-redis-usage-redis-commandsTimisoara
W
18

You can set value and expiry together.

  //here key will expire after 24 hours
  client.setex(key, 24*60*60, value, function(err, result) {
    //check for success/failure here
  });

 //here key will expire at end of the day
  client.setex(key, parseInt((new Date().setHours(23, 59, 59, 999)-new Date())/1000), value, function(err, result) {
    //check for success/failure here
  });
Wendel answered 10/7, 2016 at 19:54 Comment(1)
its work but better to ignore this command .. because in redis document :" Note: Since the SET command options can replace SETNX, SETEX, PSETEX, it is possible that in future versions of Redis these three commands will be deprecated and finally removed. " redis set commandSchroder

© 2022 - 2024 — McMap. All rights reserved.