Skip to content

Commit 1099983

Browse files
committed
refactor async_ng code to introduce random delay in MyAsyncNGBO
1 parent e3dc08d commit 1099983

File tree

2 files changed

+14
-20
lines changed

2 files changed

+14
-20
lines changed

demo/python/async_ng/bo.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22
from msg import MyMessage
33

44
import time
5+
import random
56

67
class MyAsyncNGBO(BusinessOperation):
78
def on_message(self, request):
89
print(f"Received message: {request.message}")
9-
time.sleep(1)
10-
return MyMessage(message=f"Hello, {request.message}")
10+
rand = random.randint(1, 10)
11+
time.sleep(rand)
12+
return MyMessage(message=f"Hello, {request.message} after {rand} seconds")
1113

1214

demo/python/async_ng/bp.py

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,25 @@
11
import asyncio
2-
import sys,os
3-
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..', 'src')))
2+
import random
3+
44
from iop import BusinessProcess
55
from msg import MyMessage
66

77

88
class MyAsyncNGBP(BusinessProcess):
99

1010
def on_message(self, request):
11-
import time
12-
start_time = time.time()
11+
1312
results = asyncio.run(self.await_response(request))
14-
end_time = time.time()
15-
print(f"Time taken: {end_time - start_time} seconds")
16-
self.log_info(f"Time taken: {end_time - start_time} seconds")
13+
1714
for result in results:
18-
print(f"Received response: {result.message}")
15+
self.log_info(f"Received response: {result.message}")
1916

2017
async def await_response(self, request):
21-
msg_one = MyMessage(message="Message1")
22-
msg_two = MyMessage(message="Message2")
23-
24-
# use asyncio.gather to send multiple requests asynchronously
25-
# using the send_request_async_ng method
26-
tasks = [self.send_request_async_ng("Python.MyAsyncNGBO", msg_one, timeout=5),
27-
self.send_request_async_ng("Python.MyAsyncNGBO", msg_two, timeout=-1)]
18+
# create 1 to 10 messages
19+
tasks = []
20+
for i in range(random.randint(1, 10)):
21+
tasks.append(self.send_request_async_ng("Python.MyAsyncNGBO",
22+
MyMessage(message=f"Message {i}")))
2823

2924
return await asyncio.gather(*tasks)
3025

31-
if __name__ == "__main__":
32-
bp = MyAsyncNGBP()
33-
bp.on_message(None)

0 commit comments

Comments
 (0)