如何在 Python 中在给定时间运行函数?
例如:
run_it_at(func, '2012-07-17 15:50:00')
它会在2012-07-17 15:50:00运行函数func
。
我试过 sched.scheduler ,但它没有启动我的功能。
import time as time_module
scheduler = sched.scheduler(time_module.time, time_module.sleep)
t = time_module.strptime('2012-07-17 15:50:00', '%Y-%m-%d %H:%M:%S')
t = time_module.mktime(t)
scheduler_e = scheduler.enterabs(t, 1, self.update, ())
我能做什么?
最佳答案
阅读来自 http://docs.python.org/py3k/library/sched.html 的文档:
我们需要计算出延迟(以秒为单位)...
from datetime import datetime
now = datetime.now()
然后使用 datetime.strptime
解析'2012-07-17 15:50:00'(格式字符串留给你)
# I'm just creating a datetime in 3 hours... (you'd use output from above)
from datetime import timedelta
run_at = now + timedelta(hours=3)
delay = (run_at - now).total_seconds()
然后您可以使用 delay
传递到 threading.Timer
实例,例如:
threading.Timer(delay, self.update).start()
关于python - 在给定时间启动函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11523918/