[英]How to call a function only once and wait for 5 seconds before calling again inside while loop- Python
[英]How to call a function only once every X time in an infinite loop in python?
我有一个 Python 程序,其中包含在 while 循环中调用的许多函数。
我需要我的 while 循环在第一次执行循环时调用所有函数,但随后我只想每两分钟调用一次这些函数中的一个。
这是一个代码示例:
def dostuff():
print('I\'m doing stuff!')
def dosthings():
print('I\'m doing things!')
def dosomething():
print('I\'m doing something!')
if __name__ == '__main__':
while True:
dostuff()
print('I did stuff')
dosthings()
print('I did things') #this should run once every X seconds, not on all loops
dosomething()
print('I did something')
我怎样才能达到这个结果? 我必须使用多线程/多处理吗?
这里有一个快速和肮脏的单线程的演示,使用time.perf_counter()
您也可以使用time.process_time()
如果你不希望包括在睡眠中度过的时间:
import time
# Changed the quoting to be cleaner.
def dostuff():
print("I'm doing stuff!")
def dosthings():
print("I'm doing things!")
def dosomething():
print("I'm doing something!")
if __name__ == '__main__':
x = 5
clock = -x # So that (time.perf_counter() >= clock + x) on the first round
while True:
dostuff()
print('I did stuff')
if time.perf_counter() >= clock + x:
# Runs once every `x` seconds.
dosthings()
print('I did things')
clock = time.perf_counter()
dosomething()
print('I did something')
time.sleep(1) # Just to see the execution clearly.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.