Skip to content

协程中有哪两个运行任务的函数,如何使用 #107

@Sogrey

Description

@Sogrey

请描述一下什么是协程,请举例说明 #106

'''
run
'''
import asyncio
import time

async def say_after(delay,what):
    await asyncio.sleep(delay)
    print(what)

async def myfun():
    print(f'开始时间:{time.strftime("%X")}')
    await say_after(1, 'hello')
    await say_after(2,'world')

    print(f"执行完成:{time.strftime('%X')}")
asyncio.run(myfun())
'''
create_task
'''

async def myfun1():
    task1 = asyncio.create_task(
        say_after(1, 'hello')
    )
    task2 = asyncio.create_task(
        say_after(2, 'world')

    )

    print(f'开始时间:{time.strftime("%X")}')

    await task1
    await task2

    print(f'介绍时间:{time.strftime("%X")}')
asyncio.run(myfun1())

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions