Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何每N分钟重复一次功能?_Python_Multithreading_Python 3.x_Timer - Fatal编程技术网

Python 如何每N分钟重复一次功能?

Python 如何每N分钟重复一次功能?,python,multithreading,python-3.x,timer,Python,Multithreading,Python 3.x,Timer,在我的python脚本中,我希望每N分钟重复一次函数,当然,主线程也必须继续工作。在主线程中,我有以下内容: # something # ...... while True: # something else sleep(1) 那么,如何创建一个每N分钟执行一次的函数(我想是在另一个线程中)?我应该使用定时器,甚至是线程吗?我有点困惑。使用线程 import threading def hello_world(): threading.Timer(60.0, hello_wo

在我的python脚本中,我希望每N分钟重复一次函数,当然,主线程也必须继续工作。在主线程中,我有以下内容:

# something
# ......
while True:
  # something else
  sleep(1)
那么,如何创建一个每N分钟执行一次的函数(我想是在另一个线程中)?我应该使用定时器,甚至是线程吗?我有点困惑。

使用线程

import threading

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

hello_world()

这是一个不错的答案,但它引入了一个漂移(总是比间隔至少长),随着时间的推移更准确: