Home > Backend Development > Python Tutorial > Handling Python event loop shutdown without exceptions

Handling Python event loop shutdown without exceptions

DDD
Release: 2024-12-26 10:04:10
Original
829 people have browsed it

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)

Copy after login

The above is the detailed content of Handling Python event loop shutdown without exceptions. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template