非轮询/非阻塞计时器?

新手上路,请多包涵

到目前为止,我发现的最佳解决方案是只使用 sleep() 函数。我想在定时器到期事件发生时运行我自己的回调函数。有没有任何事件驱动的方法来解决这个问题?

 from time import sleep

# Sleep for a minute
time.sleep(60)

原文由 tarabyte 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 711
1 个回答

有一个内置的简单解决方案,使用 线程 模块:

 import threading

timer = threading.Timer(60.0, callback)
timer.start()  # after 60 seconds, 'callback' will be called

## (in the meanwhile you can do other stuff...)

您还可以将 args 和 kwargs 传递给回调。看 这里

原文由 Bach 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题