DEV Community

Cover image for Handling Python event loop shutdown without exceptions
Talles L
Talles L

Posted on

Handling Python event loop shutdown without exceptions

#!/usr/bin/env python3

from asyncio import gather, new_event_loop, sleep, Event, set_event_loop
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.')

# Create the shutdown event
shutdown = Event()

# Set up a new event loop and make it the current loop
event_loop = new_event_loop()
set_event_loop(event_loop)

# Set up signal handlers
event_loop.add_signal_handler(SIGINT, shutdown_signaled)
event_loop.add_signal_handler(SIGTERM, shutdown_signaled)

# Combine the tasks
combined_tasks = gather(small_work(shutdown), big_work(shutdown))

# Run the tasks and block until they complete
event_loop.run_until_complete(combined_tasks)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)