bbartling
bbartling

Reputation: 3494

asyncio run until complete not forever

Could anyone give me a tip on how to run asyncio script to stop when complete? I know its something to do with how I am setting the main loop to run... in this portion of the complete code but what ever I try from what I can find online it doesnt work.

loop = asyncio.get_event_loop()

try:
    asyncio.ensure_future(firstWorker())
    asyncio.ensure_future(secondWorker())
    loop.run_forever()

The script below is just something made up attempting to compile randon data into a pandas dataframe when the script completes but I cant get it to complete! Any tips greatly appreciated...

complete code:

import asyncio
import pandas as pd
from datetime import datetime
import random


data = []

async def firstWorker():
    for _ in range(5):
        await asyncio.sleep(1)

        things = {}

        stamp = datetime.now()

        temperature1 = (random.random() * 20) - 5
        print(temperature1)

        things['Date'] = stamp
        things['temperature1'] = temperature1

        data.append(things)



async def secondWorker():
    for _ in range(5):
        await asyncio.sleep(1)

        stuff = {}

        stamp = datetime.now()

        temperature2 = (random.random() * 40) - 15
        print(temperature2)

        stuff['Date'] = stamp
        stuff['temperature2'] = temperature2


        data.append(stuff)



loop = asyncio.get_event_loop()

try:
    asyncio.ensure_future(firstWorker())
    asyncio.ensure_future(secondWorker())
    loop.run_forever()

except KeyboardInterrupt:
    pass

finally:
    print("Closing Loop")
    loop.close()


    master_data = pd.DataFrame(data)
    master_data.columns = ['Date','temperature1','temperature2']

    master_data.to_csv('master_data.csv')

Upvotes: 2

Views: 1307

Answers (1)

ConorSheehan1
ConorSheehan1

Reputation: 1725

You probably want asyncio.gather and run_until_complete

async def main():
    await asyncio.gather(firstWorker(), secondWorker())

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

Upvotes: 1

Related Questions