skip to Main Content

I am using node-redis. I have a cron job that updates my db and I have redis cache that caches the db response.

The problem I’m having is that my cron job runs everyday at 12am, however I can only set redis cache to expire in x seconds from now. Is there a way to make node-redis cache expire everyday at 12am exactly. Thanks.

Code:

const saveResult = await SET_CACHE_ASYNC('cacheData', response, 'EX', 15);

2

Answers


  1. yes, you can use https://redis.io/commands/expireat command, if you use https://www.npmjs.com/package/redis package as redis driver, code will be like this

    const redis = require('redis')
    const client = redis.createClient();
    const when = (Date.now()+24*60*60*1000) / 1000;
    client.expireat('cacheData', when, function(error){....};
    
    
    ``
    
    Login or Signup to reply.
  2. Recently I had the same problem with an application. My work around was creating a new timespan based on the time difference between my set and expiration time. Here is my code:

    private TimeSpan GetTimeSpanUntilNextDay(int hour)
            => new DateTime(DateTime.Now.Date.AddDays(1).Ticks).AddHours(hour) - DateTime.Now;
    

    Using the stack exchange lib for a 6 AM absolute expirition time the code looks like so:

    public async Task<bool> SetEntranceAsync(string key, MYTYPE unserializedObject)
    {
        var db = _multiplexer.GetDatabase();
        var jsonValue = JsonConvert.SerializeObject(unserializedObject);
    
        return await db.StringSetAsync(key, jsonValue, GetTimeSpanUntilNextDay(6));
    }
    

    I used C# but you should be able to do the trick in any language.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search