#! /usr/bin/env python3from asyncio import gather, get_event_loop, sleep, Eventfrom signal import SIGINT, SIGTERMdef 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 shutdownshutdown = 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 themevent_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 onecombined_tasks = gather(small_work(shutdown), big_work(shutdown))# run our tasks and blockevent_loop.run_until_complete(combined_tasks)
登录后复制
以上就是处理 Python 事件循环关闭,无异常的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2174826.html