如何在 python 的无限循环中每隔 X 次只调用一次函数?

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')

我怎样才能达到这个结果?我必须使用 multithreading/multiprocessing 吗?

这是一个快速简单的单线程演示,如果您不想包括睡眠时间,请使用 time.perf_counter(), you can alternatively use 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.

See it live