[英]python threading multiple functions every minute
我有几个函数想同时在无限循环中运行,但是所有函数应以不同的间隔运行。 例如,以下代码:
while True:
functionA()
after 1 minute repeat
functionB()
after 2 minutes repeat
我知道使用time.sleep或dateime.now()很热,但是我不知道如何在同一文件中让functionA和B彼此独立地运行和等待。
from threading import Timer
class Interval(object):
"""Interface wrapper for re-occuring functions."""
def __init__(self, f, timeout):
super(Interval, self).__init__()
self.timeout = timeout
self.fn = f
self.next = None
self.done = False
self.setNext()
def setNext(self):
"""Queues up the next call to the intervaled function."""
if not self.done:
self.next = Timer(self.timeout, self.run)
self.next.start()
return self
def run(self):
"""Starts the interval."""
self.fn()
self.setNext()
return self
def stop(self):
"""Stops the interval. Cancels any pending call."""
self.done = True
self.next.cancel()
return self
将函数和超时作为参数传递。 线程模块中的Timer类完成了您所需的大部分操作(经过一定时间后运行一个函数),我添加的包装器类仅添加了重复项,使其易于启动,停止,传递等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.