tags:

views:

126

answers:

2

I know that I can cause a thread to sleep for a specific amount of time with:

time.sleep(NUM)

How can I make a thread sleep until 2AM? Do I have to do math to determine the number of seconds until 2AM? Or is there some library function?

( Yes, I know about cron and equivalent systems in Windows, but I want to sleep my thread in python proper and not rely on external stimulus or process signals.)

+1  A: 

Here's a half-ass solution that doesn't account for clock jitter or adjustment of the clock. See comments for ways to get rid of that.

import time
import datetime

# if for some reason this script is still running
# after a year, we'll stop after 365 days
for i in xrange(0,365):
    # sleep until 2AM
    t = datetime.datetime.today()
    future = datetime.datetime(t.year,t.month,t.day+(t.hour >= 2 ),2,0)
    time.sleep((future-t).seconds)

    # do 2AM stuff
Ross Rogers
`t.day + (t.hour >= 2)` would be a (possibly non-Pythonic) solution to the "between 0000 and 0200" problem. Also, I'd put the `sleep` in a loop waking up periodically, in case the clock is adjusted or we wake up early, but I don't think that's very important.
ephemient
+1 on comment. excellent solution for 0-2AM time. Thanks!
Ross Rogers
BTW, it's worth noting that naive use of *only* the `seconds` attribute can lead to unexpected results. It contains only the "remainder" of division by one day, so to speak, so if the duration is longer than one day, you'd need to add `.days * 24*3600`. Obviously not a problem in this case, but something that catches the odd person who's unfamiliar with datetime objects.
Peter Hansen
+1  A: 

One possible approach is to sleep for an hour. Every hour, check if the time is in the middle of the night. If so, proceed with your operation. If not, sleep for another hour and continue.

If the user were to change their clock in the middle of the day, this approach would reflect that change. While it requires slightly more resources, it should be negligible.

carl