Python 如何每 N 分钟重复一次函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35410498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:24:51  来源:igfitidea点击:

How to repeat a function every N minutes?

pythonmultithreadingpython-3.xtimer

提问by Steven

In my python script I want to repeat a function every N minutes, and, of course, the main thread has to keep working as well. In the main thread I have this:

在我的 python 脚本中,我想每 N 分钟重复一个函数,当然,主线程也必须继续工作。在主线程中,我有这个:

# something
# ......
while True:
  # something else
  sleep(1)

So how can I create a function (I guess, in another thread) which executes every N minutes? Should I use a timer, or Even, or just a Thread? I'm a bit confused.

那么如何创建一个每 N 分钟执行一次的函数(我猜是在另一个线程中)?我应该使用计时器,还是 Even,或者只是一个线程?我有点困惑。

采纳答案by danidee

use a thread

使用线程

import threading

def hello_world():
    threading.Timer(60.0, hello_world).start() # called every minute
    print("Hello, World!")

hello_world()