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

标签 python multithreading while-loop multiprocessing infinite-loop

我有一个 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()如果您不想包括 sleep 时间:

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

关于python - 如何在Python中的无限循环中每X次调用一次函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57260724/

相关文章:

java - Hibernate session 和并发

php - jquery和php,加载图片并使用每个图片的src

python - 在 Python 中使用 argparse - 和默认文件关联

python - 语法错误: Python keyword not valid identifier in numexpr query

Python:传递函数更多信息是一件坏事吗?

Python While循环计算最小公倍数

while 循环的 Pythonic 枚举

python - 这段关于加泰罗尼亚数字的 Python 代码有什么问题?

来自嵌套字典的 Python 数据类

linux - 为什么在支持 X 线程的硬件中使用 X 线程?为什么不是 X-1 线程?