#!/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)
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.
Community matters
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)