简体   繁体   中英

How to execute an asychronous function inside a loop whithout calling it multiple times?

I am currently writing a program where I have a while True loop in which I want to call two functions. Before they are called some information is gathered which determines if they should be called (and I can't do that inside the functions). The functions take some time to execute but they must not interrupt the loop execution (they should be executed asynchronously). And they also must not be executed when there already is an instance of each function running. How can I implement this?

I have already looked into asyncio but couldn't figure out how to apply it to my problem. In the following code example you can see how I imagine it to work.

def B_sync_func():
    global B
    B = True
    #do time consuming stuff
    B = False
    return

def A_async_func():
    global A
    A = True
    #do time consuming stuff
    A = False
    return

A = False
B = False

while True:
    info = data_gathering()

    if execute_A(info) and !A:
        A_async_func()

    if execute_B(info) and !B:
        B_async_func()

If you just need to execute the async function to be called again after it finished, you can just make the function call itself again:

def async_func():
    # do stuff
    async_func()

async_func()

You just invoke the function once and it invokes itself every time it finishes. That way you can achieve the same behavior as you do when using an infinite while loop but you the function can complete before it's called again and it could even interrupt itself.

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