|
| 1 | +import asyncio |
| 2 | +from dataclasses import dataclass |
| 3 | +from datetime import timedelta |
| 4 | + |
| 5 | +from temporalio import activity, workflow |
| 6 | +from temporalio.client import Client |
| 7 | +from temporalio.worker import Worker |
| 8 | + |
| 9 | + |
| 10 | +# While we could use multiple parameters in the activity, Temporal strongly |
| 11 | +# encourages using a single dataclass instead which can have fields added to it |
| 12 | +# in a backwards-compatible way. |
| 13 | +@dataclass |
| 14 | +class ComposeGreetingInput: |
| 15 | + greeting: str |
| 16 | + name: str |
| 17 | + |
| 18 | + |
| 19 | +# Basic activity that logs and does string concatenation |
| 20 | +@activity.defn |
| 21 | +async def compose_greeting(input: ComposeGreetingInput) -> str: |
| 22 | + activity.logger.info("Running activity with parameter %s" % input) |
| 23 | + return f"{input.greeting}, {input.name}!" |
| 24 | + |
| 25 | + |
| 26 | +# Basic workflow that logs and invokes an activity |
| 27 | +@workflow.defn |
| 28 | +class GreetingWorkflow: |
| 29 | + @workflow.run |
| 30 | + async def run(self, name: str) -> str: |
| 31 | + workflow.logger.info("Running workflow with parameter %s" % name) |
| 32 | + return await workflow.execute_activity( |
| 33 | + compose_greeting, |
| 34 | + ComposeGreetingInput("Hello", name), |
| 35 | + start_to_close_timeout=timedelta(seconds=10), |
| 36 | + ) |
| 37 | + |
| 38 | + |
| 39 | +async def main(): |
| 40 | + # Uncomment the lines below to see logging output |
| 41 | + # import logging |
| 42 | + # logging.basicConfig(level=logging.INFO) |
| 43 | + |
| 44 | + # Start client |
| 45 | + client = await Client.connect("localhost:7233") |
| 46 | + |
| 47 | + # Run a worker for the workflow |
| 48 | + async with Worker( |
| 49 | + client, |
| 50 | + task_queue="hello-activity-task-queue", |
| 51 | + workflows=[GreetingWorkflow], |
| 52 | + activities=[compose_greeting], |
| 53 | + # If the worker is only running async activities, you don't need |
| 54 | + # to supply an activity executor because they run in |
| 55 | + # the worker's event loop. |
| 56 | + ): |
| 57 | + |
| 58 | + # While the worker is running, use the client to run the workflow and |
| 59 | + # print out its result. Note, in many production setups, the client |
| 60 | + # would be in a completely separate process from the worker. |
| 61 | + result = await client.execute_workflow( |
| 62 | + GreetingWorkflow.run, |
| 63 | + "World", |
| 64 | + id="hello-activity-workflow-id", |
| 65 | + task_queue="hello-activity-task-queue", |
| 66 | + ) |
| 67 | + print(f"Result: {result}") |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == "__main__": |
| 71 | + asyncio.run(main()) |
0 commit comments