userx
userx

Reputation: 886

Resetting redis keys daily using twisted

I am using twisted engine along with Redis. I need to clear some redis keys daily (at 12 oclock, to maintain day wise data).

I tried to use task.LoopingCall which works fine. It clears keys after 24 hrs but problem is, to work this, I need to start engine at 12 oclock. So LoopingCall can be set for 24 hrs.

Instead of starting engine at 12 oclock, is there any better way using twisted & redis themselves?

As per my knowledge, we can do this using crone job. But is it good or is there any alternative ?

Upvotes: 1

Views: 145

Answers (1)

Glyph
Glyph

Reputation: 31910

Assuming that you mean you want to clear those keys at 12:00 AM local time, first you'll want to install the tzlocal package:

$ pip install tzlocal

and then you can compute the time until the next timezone, something like this:

from tzlocal import get_localzone

zone = get_localzone()

import datetime
now = datetime.datetime.now(zone)
next_midnight = (now.replace(hour=0, minute=0, second=0, microsecond=0) +
                 datetime.timedelta(days=1))

delta = then - now
until_next_midnight = delta.total_seconds()

And finally, you can start your LoopingCall at that point, something like this:

call = LoopingCall(...)
reactor.callLater(
    until_next_midnight,
    lambda: call.start(datetime.timedelta(days=1).total_seconds())
)

Upvotes: 1

Related Questions