Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how can I put a thread to sleep until a specific time?

Tags:

python

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

like image 312
Ross Rogers Avatar asked Jan 08 '10 22:01

Ross Rogers


1 Answers

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,2,0)     if t.hour >= 2:         future += datetime.timedelta(days=1)     time.sleep((future-t).total_seconds())          # do 2AM stuff 
like image 181
Ross Rogers Avatar answered Sep 24 '22 17:09

Ross Rogers