我想在 python 中安排一个重复的定时事件,如下所示: “在时间 X 启动函数 Y(在单独的线程中)并每小时重复一次”
“X”是固定时间戳
代码应该是跨平台的,所以我想避免使用像“cron”这样的外部程序来执行此操作。
代码摘录:
import threading threading.Timer(10*60, mail.check_mail).start() #... SET UP TIMED EVENTS HERE while(1): print("please enter command") try: command = raw_input() except: continue handle_command(command)
最佳答案
创建 dateutil.rrule
, rr
作为您的日程安排,然后在您的线程中使用如下循环:
for ts in rr:
now = datetime.now()
if ts < now:
time.sleep((now - ts).total_seconds())
# do stuff
或者更好的解决方案,可以考虑时钟变化:
ts = next(rr)
while True:
now = datetime.now()
if ts < now:
time.sleep((now - ts).total_seconds() / 2)
continue
# do stuff
ts = next(rr)
关于python - 如何在Python中安排定时事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10700500/