|
| 1 | +import asyncio |
| 2 | +import time |
| 3 | + |
| 4 | +import trio |
| 5 | +import trio_asyncio |
| 6 | +from temporalio import activity |
| 7 | + |
| 8 | + |
| 9 | +# An asyncio-based async activity |
| 10 | +@activity.defn |
| 11 | +async def say_hello_activity_async(name: str) -> str: |
| 12 | + # Demonstrate a sleep in both asyncio and Trio, showing that both asyncio |
| 13 | + # and Trio primitives can be used |
| 14 | + |
| 15 | + # First asyncio |
| 16 | + activity.logger.info("Sleeping in asyncio") |
| 17 | + await asyncio.sleep(0.1) |
| 18 | + |
| 19 | + # Now Trio. We have to invoke the function separately decorated. |
| 20 | + # We cannot use the @trio_as_aio decorator on the activity itself because |
| 21 | + # it doesn't use functools wrap or similar so it doesn't respond to things |
| 22 | + # like __name__ that @activity.defn needs. |
| 23 | + return await say_hello_in_trio_from_asyncio(name) |
| 24 | + |
| 25 | + |
| 26 | +@trio_asyncio.trio_as_aio |
| 27 | +async def say_hello_in_trio_from_asyncio(name: str) -> str: |
| 28 | + activity.logger.info("Sleeping in Trio (from asyncio)") |
| 29 | + await trio.sleep(0.1) |
| 30 | + return f"Hello, {name}! (from asyncio)" |
| 31 | + |
| 32 | + |
| 33 | +# A thread-based sync activity |
| 34 | +@activity.defn |
| 35 | +def say_hello_activity_sync(name: str) -> str: |
| 36 | + # Demonstrate a sleep in both threaded and Trio, showing that both |
| 37 | + # primitives can be used |
| 38 | + |
| 39 | + # First, thread-blocking |
| 40 | + activity.logger.info("Sleeping normally") |
| 41 | + time.sleep(0.1) |
| 42 | + |
| 43 | + # Now Trio. We have to use Trio's thread sync tools to run trio calls from |
| 44 | + # a different thread. |
| 45 | + return trio.from_thread.run(say_hello_in_trio_from_sync, name) |
| 46 | + |
| 47 | + |
| 48 | +async def say_hello_in_trio_from_sync(name: str) -> str: |
| 49 | + activity.logger.info("Sleeping in Trio (from thread)") |
| 50 | + await trio.sleep(0.1) |
| 51 | + return f"Hello, {name}! (from thread)" |
0 commit comments