Pythontime.sleep每隔一定的时间间隔和函数
Python time.sleep every regular time intervals and function
我需要每 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()?我确定它与线程有关,但找不到合适的示例。
示例代码。
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()
在此处查看更多信息:
http://www.bogotobogo.com/python/Multithread/python_multithreading_subclassing_Timer_Object.php
所以在你的情况下会是:
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)
我需要每 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()?我确定它与线程有关,但找不到合适的示例。
示例代码。
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()
在此处查看更多信息: http://www.bogotobogo.com/python/Multithread/python_multithreading_subclassing_Timer_Object.php
所以在你的情况下会是:
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)