Python time.sleep每个固定的时间间隔和函数

Python time.sleep每个固定的时间间隔和函数,python,python-multithreading,Python,Python Multithreading,我需要每10秒开始执行一个函数foo(),foo()函数需要1到3秒之间的随机时间来执行 import time import datetime def foo(): # ... code which takes a random time between 1 and 3 seconds to be executed while True: foo() time.sleep(10) 当然,在上面的示例中,函数foo()不是每10秒执行一次,而是每10+随机秒执行一次

我需要每10秒开始执行一个函数foo(),foo()函数需要1到3秒之间的随机时间来执行

import time
import datetime

def foo():
    # ... code which takes a random time between 1 and 3 seconds to be executed

while True:
    foo()
    time.sleep(10)
当然,在上面的示例中,函数foo()不是每10秒执行一次,而是每10+随机秒执行一次

是否有一种方法可以开始执行foo(),每次执行10秒?我确信这与线程有关,但找不到合适的示例。

示例代码

import time
import datetime

def foo():
    # ... code which takes a random time between 1 and 3 seconds to be executed

while True:
    start = time.time() 
    foo(random number)
    end = time.time()  - start
    time.sleep(10 - end)

是的,它与线程相关,因为您希望生成一个不同的线程来异步执行您的函数-父进程将等待10秒,而不管线程执行所需的时间

这是在python中执行此操作的标准方法:

import threading

def print_some():
  threading.Timer(10.0, print_some).start()
  print "Hello!"

print_some()
请参阅此处的更多信息:

因此,在您的情况下,它将是:

import threading
import time

def foo():
    threading.Timer(10.0, foo).start()
    print("hello")

if __name__ == '__main__':
    foo()

如果你想在这里穿线,就去吧

import threading

def foo():
   # does stuff

while True:
   t = threading.Thread(target=foo)
   t.start()
   time.sleep(10)