#! /usr/bin/env python3
from asyncio import gather, get_event_loop, sleep, Event
from signal import SIGINT, SIGTERM
def shutdown_signaled():
print('Shutdown requested.')
shutdown.set()
async def small_work(shutdown):
while not shutdown.is_set():
await sleep(0.5)
print('Small work is done!')
print('Exited small work.')
async def big_work(shutdown):
while not shutdown.is_set():
await sleep(5)
print('Big work is done!!!')
print('Exited big work.')
# when this event is set the application is ready to shutdown
shutdown = Event()
# setting up our own handler for Ctrl+C and SIGTERM (sent with kill)
# by setting this handler running tasks will not get an exception thrown at them
event_loop = get_event_loop()
event_loop.add_signal_handler(SIGINT, shutdown_signaled)
event_loop.add_signal_handler(SIGTERM, shutdown_signaled)
# combining our two tasks as one
combined_tasks = gather(small_work(shutdown), big_work(shutdown))
# run our tasks and block
event_loop.run_until_complete(combined_tasks)
以上就是处理 Python 事件循环关闭,无异常的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号