bless1204
bless1204

Reputation: 653

Redis - How to expire key daily

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!

Upvotes: 38

Views: 103820

Answers (4)

codewithsg
codewithsg

Reputation: 702

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)

Upvotes: 35

loretoparisi
loretoparisi

Reputation: 16271

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.

Upvotes: 37

Praveena
Praveena

Reputation: 6941

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
  });

Upvotes: 18

laggingreflex
laggingreflex

Reputation: 34627

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));

Upvotes: 53

Related Questions