首页 > 后端开发 > Python教程 > 处理 Python 事件循环关闭,无异常

处理 Python 事件循环关闭,无异常

DDD
发布: 2024-12-26 10:04:10
原创
785 人浏览过

Handling Python event loop shutdown without exceptions

#! /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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板