asyncio — asynchronous I/O scheduler
Example:
import asyncio
async def blink(led, period_ms):
while True:
led.on()
await asyncio.sleep_ms(5)
led.off()
await asyncio.sleep_ms(period_ms)
async def main(led1, led2):
asyncio.create_task(blink(led1, 700))
asyncio.create_task(blink(led2, 400))
await asyncio.sleep_ms(10_000)
# Running on a generic board
from machine import Pin
asyncio.run(main(Pin('PD14',Pin.OUT), Pin('PG3',Pin.OUT)))
Core functions
- asyncio.create_task(coro)
Create a new task from the given coroutine and schedule it to run.
Returns the corresponding
Taskobject.
- asyncio.run(coro)
Create a new task from the given coroutine and run it until it completes.
Returns the value returned by coro.
- asyncio.sleep(t)
Sleep for t seconds (can be a float).
This is a coroutine.
- asyncio.sleep_ms(t)
Sleep for t milliseconds.
This is a coroutine, and a MicroPython extension.
Additional functions
- asyncio.wait_for(awaitable, timeout)
Wait for the awaitable to complete, but cancel it if it takes longer than timeout seconds. If awaitable is not a task then a task will be created from it.
If a timeout occurs, it cancels the task and raises
asyncio.TimeoutError: this should be trapped by the caller. The task receivesasyncio.CancelledErrorwhich may be ignored or trapped usingtry...exceptortry...finallyto run cleanup code.Returns the return value of awaitable.
This is a coroutine.
- asyncio.wait_for_ms(awaitable, timeout)
Similar to
wait_forbut timeout is an integer in milliseconds.This is a coroutine, and a MicroPython extension.
- asyncio.gather(*awaitables, return_exceptions=False)
Run all awaitables concurrently. Any awaitables that are not tasks are promoted to tasks.
Returns a list of return values of all awaitables.
This is a coroutine.
class Task
- class asyncio.Task
This object wraps a coroutine into a running task. Tasks can be waited on using
await task, which will wait for the task to complete and return the return value of the task.Tasks should not be created directly, rather use
create_taskto create them.
- Task.cancel()
Cancel the task by injecting
asyncio.CancelledErrorinto it. The task may ignore this exception. Cleanup code may be run by trapping it, or viatry ... finally.
class Event
- class asyncio.Event
Create a new event which can be used to synchronise tasks. Events start in the cleared state.
- Event.is_set()
Returns
Trueif the event is set,Falseotherwise.
- Event.set()
Set the event. Any tasks waiting on the event will be scheduled to run.
Note: This must be called from within a task. It is not safe to call this from an IRQ, scheduler callback, or other thread. See
ThreadSafeFlag.
- Event.clear()
Clear the event.
- Event.wait()
Wait for the event to be set. If the event is already set then it returns immediately.
This is a coroutine.
class ThreadSafeFlag
- class asyncio.ThreadSafeFlag
Create a new flag which can be used to synchronise a task with code running outside the asyncio loop, such as other threads, IRQs, or scheduler callbacks. Flags start in the cleared state.
- ThreadSafeFlag.set()
Set the flag. If there is a task waiting on the flag, it will be scheduled to run.
- ThreadSafeFlag.clear()
Clear the flag. This may be used to ensure that a possibly previously-set flag is clear before waiting for it.
- ThreadSafeFlag.wait()
Wait for the flag to be set. If the flag is already set then it returns immediately. The flag is automatically reset upon return from
wait.A flag may only be waited on by a single task at a time.
This is a coroutine.
class Lock
- class asyncio.Lock
Create a new lock which can be used to coordinate tasks. Locks start in the unlocked state.
In addition to the methods below, locks can be used in an
async withstatement.
- Lock.locked()
Returns
Trueif the lock is locked, otherwiseFalse.
- Lock.acquire()
Wait for the lock to be in the unlocked state and then lock it in an atomic way. Only one task can acquire the lock at any one time.
This is a coroutine.
- Lock.release()
Release the lock. If any tasks are waiting on the lock then the next one in the queue is scheduled to run and the lock remains locked. Otherwise, no tasks are waiting an the lock becomes unlocked.
Event Loop
- asyncio.new_event_loop()
Reset the event loop and return it.
Note: since MicroPython only has a single event loop this function just resets the loop’s state, it does not create a new one.
- class asyncio.Loop
This represents the object which schedules and runs tasks. It cannot be created, use
get_event_loopinstead.
- Loop.run_until_complete(awaitable)
Run the given awaitable until it completes. If awaitable is not a task then it will be promoted to one.
- Loop.stop()
Stop the event loop.
- Loop.close()
Close the event loop.
- Loop.set_exception_handler(handler)
Set the exception handler to call when a Task raises an exception that is not caught. The handler should accept two arguments:
(loop, context).
- Loop.get_exception_handler()
Get the current exception handler. Returns the handler, or
Noneif no custom handler is set.
- Loop.default_exception_handler(context)
The default exception handler that is called.
- Loop.call_exception_handler(context)
Call the current exception handler. The argument context is passed through and is a dictionary containing keys:
'message','exception','future'.