简体   繁体   中英

How to call a function only once every X time in an infinite loop in python?

I have a Python program with many functions that I call inside a while loop.

I need my while loop to call all the functions the first time it does the loop, but then I would want to call one of those functions only once every two minutes.

Here is a code example:

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

How can I achieve this result? Have I to use multithreading/multiprocessing?

Here's a quick-and-dirty single threaded demo, using time.perf_counter() , you can alternatively use time.process_time() if you don't want to include time spent in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM