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()