I have the following code:
@asyncio.coroutine
def do_something_periodically():
while True:
asyncio.async(my_expensive_operation())
yield from asyncio.sleep(my_interval)
if shutdown_flag_is_set:
print("Shutting down")
break
I run this function until complete. The problem occurs when shutdown is set - the function completes and any pending tasks are never run.
This is the error:
task: <Task pending coro=<report() running at script.py:33> wait_for=<Future pending cb=[Task._wakeup()]>>
How do I schedule a shutdown correctly?
To give some context, I'm writing a system monitor which reads from /proc/stat every 5 seconds, computes the cpu usage in that period, and then sends the result to a server. I want to keep scheduling these monitoring jobs until I receive sigterm, when I stop scheduling, wait for all current jobs to finish, and exit gracefully.
yield from my_expensive_operation() \n yield from asyncio.sleep(my_interval - timer() % my_interval)
instead? – Mientaoasync()
(remove finished jobs). In principle, you could get all current Task instance (there might be a class attribute). – Mientao