python - 在给定时间启动函数

标签 python time scheduler

如何在 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/

相关文章:

用于将 Django 与 Facebook 集成的 Python 库

javascript - 两个日期之间的差异,以分钟为单位,小时javascript

algorithm - Hu 的算法是否适用于一般的单位长度边 DAG?

python - 使用 PIL 在正方形内绘制线条

python - 定义椭圆的网格大小

Android-减少检索数据的时间

linux - 有谁知道 fifo.c linux fifo 调度程序的文件位置?

java - 需要使用 android studio 在复选框上应用时间调度程序

python - 对于Python, "import gcsfs"或 "from google.cloud import storage"与GCS交互

performance - 导入依赖项来完成特定任务是否更有效,或者没有依赖项的编码更好?