在 Python 中,如何让线程休眠直到特定时间? [英] In Python, how can I put a thread to sleep until a specific time?
问题描述
我知道我可以通过以下方式使线程休眠特定时间:
I know that I can cause a thread to sleep for a specific amount of time with:
time.sleep(NUM)
如何让线程休眠到凌晨 2 点?我是否必须做数学计算才能确定到凌晨 2 点的秒数?或者有什么库函数?
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?
(是的,我知道 Windows 中的 cron 和等效系统,但我想在 python 中适当地睡眠我的线程,而不是依赖外部刺激或进程信号.)
( 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.)
推荐答案
这是一个不考虑时钟抖动或时钟调整的半解决方案.有关摆脱这种情况的方法,请参阅评论.
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
这篇关于在 Python 中,如何让线程休眠直到特定时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!