[英]python threading multiple functions every minute
I have several functions I would like to run in an infinite loop simultaneously, but all functions should be run at different intervals. 我有几个函数想同时在无限循环中运行,但是所有函数应以不同的间隔运行。 For example, the following code: 例如,以下代码:
while True:
functionA()
after 1 minute repeat
functionB()
after 2 minutes repeat
I know hot to work with time.sleep or dateime.now(), but I do not know how to get functionA and B to run and wait independently of each other in the same file. 我知道使用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
Pass the functions and timeouts as arguments. 将函数和超时作为参数传递。 The Timer class from the threading module does most of what you need (running a function after a certain time has passed) the wrapper class I added just adds the repetition, makes it easy to start it, stop it, pass it around, etc. 线程模块中的Timer类完成了您所需的大部分操作(经过一定时间后运行一个函数),我添加的包装器类仅添加了重复项,使其易于启动,停止,传递等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.