asyncio Event事件旨在向多个协程发出信号,因此协程方法可被阻塞,直到Event被“设置”为止。
使用事件循环构建一个清理模式:
import asyncio
import logging
import random
logging.basicConfig(level=logging.INFO)
async def busy_loop(interval, work, worker, shutdown_event):
"""持续工作,直到shutdown_event被设置"""
while not shutdown_event.is_set():
await worker(work)
await asyncio.sleep(interval)
logging.info('shutdown event set, exit busy_loop')
return work
async def cleanup(mess, shutdown_event):
"""阻塞等待shutdown_event被设置,然后清理mess垃圾"""
await shutdown_event.wait()
logging.info('cleaning up the mess(脏东西/粪便): %s', mess)
# 在这里添加清理逻辑
async def shutdown(delay, shutdown_event):
"""阻塞等待delay秒,然后设置shutdown_event"""
await asyncio.sleep(delay)
shutdown_event.set()
async def add_mess(mess_pile, ):
"""向mess_pile垃圾堆中添加一个mess垃圾"""
mess = random.randint(1, 100)
logging.info('adding mess: %s', mess)
mess_pile.append(mess)
async def main():
shutdown_event = asyncio.Event()
shutdown_delay = 10
work = []
await asyncio.gather(*[shutdown(shutdown_delay, shutdown_event),
cleanup(work, shutdown_event),
busy_loop(1, work, add_mess, shutdown_event)])
asyncio.run(main())
打印 INFO:root:adding mess: 43 INFO:root:adding mess: 43 INFO:root:adding mess: 78 INFO:root:adding mess: 18 INFO:root:adding mess: 68 INFO:root:adding mess: 34 INFO:root:adding mess: 2 INFO:root:adding mess: 77 INFO:root:adding mess: 54 INFO:root:adding mess: 21 INFO:root:cleaning up the mess(脏东西/粪便): [43, 43, 78, 18, 68, 34, 2, 77, 54, 21] INFO:root:shutdown event set, exit busy_loop
知识点:
补充: