Events¤
A receiver that can be made ready directly.
Usage¤
There are cases where it is useful to be able to send a signal to
a select()
loop, for example, to stop a loop from
outside the loop itself.
To do that, you can use an Event
receiver and
call set()
on it when you want to make it
ready.
Stopping¤
The receiver will be re-activated (will keep blocking) after the current set
event is received. To stop the receiver completely, you can call
stop()
.
Example¤
Exit after printing the first 5 numbers
import asyncio
from frequenz.channels import Anycast, select, selected_from
from frequenz.channels.event import Event
channel: Anycast[int] = Anycast(name="channel")
receiver = channel.new_receiver()
sender = channel.new_sender()
stop_event = Event(name="stop")
async def do_work() -> None:
async for selected in select(receiver, stop_event):
if selected_from(selected, receiver):
print(selected.message)
elif selected_from(selected, stop_event):
print("Stop event triggered")
stop_event.stop()
break
async def send_stuff() -> None:
for i in range(10):
if stop_event.is_stopped:
break
await asyncio.sleep(1)
await sender.send(i)
async def main() -> None:
async with asyncio.TaskGroup() as task_group:
task_group.create_task(do_work(), name="do_work")
task_group.create_task(send_stuff(), name="send_stuff")
await asyncio.sleep(5.5)
stop_event.set()
asyncio.run(main())