简体   繁体   中英

Start async task in class?

I have the following code:

import asyncio

class Test:

    async def hello_world(self):
            while True:
                print("Hello World!")
                await asyncio.sleep(1)

test = Test()

loop = asyncio.get_event_loop()
# Blocking call which returns when the hello_world() coroutine is done
loop.run_until_complete(test.hello_world())
loop.close()

Is there a way to have the hello_world function starting to run from within the class (when an object of the class is created) without doing it from the outside?

Is the asynchronous constructor trick what you need? To be able to achieve such usage:

async def main():
    test = await Test()

You just need to make the asynchronous constructor return self and add an __await__ method to your class:

class Test:

    async def hello_world(self):
        while True:
            print("Hello World!")
            await asyncio.sleep(1)
        return self

    def __await__(self):
        return self.hello_world().__await__()

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