@@ -17,19 +17,15 @@ class ComposeGreetingInput:
17
17
18
18
19
19
class GreetingComposer :
20
- def __init__ (self , client : Client ) -> None :
20
+ def __init__ (self , client : Client , loop : asyncio . AbstractEventLoop ) -> None :
21
21
self .client = client
22
+ self .loop = loop
22
23
23
24
@activity .defn
24
25
def compose_greeting (self , input : ComposeGreetingInput ) -> str :
25
- # Schedule a task to complete this asynchronously . This could be done in
26
+ # Make a thread to complete this externally . This could be done in
26
27
# a completely different process or system.
27
28
print ("Completing activity asynchronously" )
28
- # Tasks stored by asyncio are weak references and therefore can get GC'd
29
- # which can cause warnings like "Task was destroyed but it is pending!".
30
- # So we store the tasks ourselves.
31
- # See https://docs.python.org/3/library/asyncio-task.html#creating-tasks,
32
- # https://bugs.python.org/issue21163 and others.
33
29
Thread (
34
30
target = self .complete_greeting ,
35
31
args = (activity .info ().task_token , input ),
@@ -47,11 +43,13 @@ def complete_greeting(self, task_token: bytes, input: ComposeGreetingInput) -> N
47
43
handle = self .client .get_async_activity_handle (task_token = task_token )
48
44
for _ in range (0 , 3 ):
49
45
print ("Waiting one second..." )
50
- asyncio .run (handle .heartbeat ())
46
+ asyncio .run_coroutine_threadsafe (handle .heartbeat (), self . loop )
51
47
time .sleep (1 )
52
48
53
49
# Complete using the handle
54
- asyncio .run (handle .complete (f"{ input .greeting } , { input .name } !" ))
50
+ asyncio .run_coroutine_threadsafe (
51
+ handle .complete (f"{ input .greeting } , { input .name } !" ), self .loop
52
+ )
55
53
56
54
57
55
@workflow .defn
@@ -72,8 +70,10 @@ async def main():
72
70
# Start client
73
71
client = await Client .connect ("localhost:7233" )
74
72
73
+ loop = asyncio .get_event_loop ()
74
+
75
75
# Run a worker for the workflow
76
- composer = GreetingComposer (client )
76
+ composer = GreetingComposer (client , loop )
77
77
async with Worker (
78
78
client ,
79
79
task_queue = "hello-async-activity-completion-task-queue" ,
0 commit comments