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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay