Skip to content

Commit ea1db3c

Browse files
committed
Improve Dispatcher examples
Split the example in 2, one for events and one for ready to execute processing, and add a match statement to make it more clear how it is intended to be used. Signed-off-by: Leandro Lucarella <[email protected]>
1 parent 85a7ff3 commit ea1db3c

File tree

1 file changed

+36
-4
lines changed

1 file changed

+36
-4
lines changed

src/frequenz/dispatch/_dispatcher.py

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,31 @@ class Dispatcher:
4848
4949
allows to receive new dispatches and ready dispatches.
5050
51-
Example:
51+
Example: Processing ready-to-execute dispatches
5252
```python
5353
import grpc.aio
54-
from frequenz.dispatch import Dispatcher
54+
55+
async def run():
56+
grpc_channel = grpc.aio.insecure_channel("localhost:50051")
57+
microgrid_id = 1
58+
service_address = "localhost:50051"
59+
60+
dispatcher = Dispatcher(microgrid_id, grpc_channel, service_address)
61+
dispatcher.start() # this will start the actor
62+
63+
ready_receiver = dispatcher.ready_to_execute.new_receiver()
64+
65+
async for dispatch in ready_receiver:
66+
print(f"Executing dispatch {dispatch.id}, due on {dispatch.start_time}")
67+
# execute the dispatch
68+
```
69+
70+
Example: Getting notification about dispatch lifecycle events
71+
```python
72+
from typing import assert_never
73+
74+
import grpc.aio
75+
from frequenz.dispatch import Created, Deleted, Dispatcher, Updated
5576
5677
5778
async def run():
@@ -60,8 +81,19 @@ async def run():
6081
service_address = "localhost:50051"
6182
dispatcher = Dispatcher(microgrid_id, grpc_channel, service_address)
6283
dispatcher.start() # this will start the actor
63-
events = dispatcher.lifecycle_events.new_receiver()
64-
ready = dispatcher.ready_to_execute.new_receiver()
84+
85+
events_receiver = dispatcher.lifecycle_events.new_receiver()
86+
87+
async for event in events_receiver:
88+
match event:
89+
case Created(dispatch):
90+
print(f"A dispatch was created: {dispatch}")
91+
case Deleted(dispatch):
92+
print(f"A dispatch was deleted: {dispatch}")
93+
case Updated(dispatch):
94+
print(f"A dispatch was updated: {dispatch}")
95+
case _ as unhandled:
96+
assert_never(unhandled)
6597
```
6698
"""
6799

0 commit comments

Comments
 (0)