python coroutine,asyncio,yield

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python coroutine,asyncio,yield相关的知识,希望对你有一定的参考价值。


import time
from datetime import datetime
import asyncio

#@ coroutine by yield
def print_message_periodical1(interval_seconds, message='keep alive'):
    while True:
        print(f'{datetime.now()}-{message}')
        start=time.time()
        end=start+interval_seconds
        while True:
            yield
            now=time.time()
            if now>=end:
                break

def coroutine_by_yield():
    a=print_message_periodical1(1, 'one')
    b=print_message_periodical1(3, 'three')
    stack=[a,b]
    while True:
        for task in stack:
            next(task)

#@ coroutine by asyncio
async def print_message_periodical2(interval_seconds,message='keep alive'):
    while True:
        print(f'{datetime.now()}-{message}')
        start = time.time()
        end = start + interval_seconds
        while True:
            await asyncio.sleep(0)
            now = time.time()
            if now >= end:
                break

def coroutine_by_asyncio():
    scheduler=asyncio.get_event_loop()
    scheduler.create_task(print_message_periodical2(1,'one'))
    scheduler.create_task(print_message_periodical2(3,'three'))
    scheduler.run_forever()


if __name__ == '__main__':
    coroutine_by_yield()
    coroutine_by_asyncio()

以上是关于python coroutine,asyncio,yield的主要内容,如果未能解决你的问题,请参考以下文章

@asyncio.coroutine 与 async def

Python asyncio run_coroutine_threadsafe 从不运行协程?

async 和 asyncio 错误 -- TypeError: 'coroutine' object is not callable

python框架fastapi, AttributeError: module 'asyncio' has no attribute 'iscoroutinefunction&

Python学习---Python的异步---asyncio模块(no-http)

async/await