|
| 1 | +package asyncactivity |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "time" |
| 7 | + |
| 8 | + "go.temporal.io/sdk/activity" |
| 9 | + "go.temporal.io/sdk/workflow" |
| 10 | +) |
| 11 | + |
| 12 | +// AsyncActivityWorkflow is a workflow definition starting two activities |
| 13 | +// asynchronously. |
| 14 | +func AsyncActivityWorkflow(ctx workflow.Context, name string) (string, error) { |
| 15 | + ao := workflow.ActivityOptions{ |
| 16 | + StartToCloseTimeout: 10 * time.Second, |
| 17 | + } |
| 18 | + ctx = workflow.WithActivityOptions(ctx, ao) |
| 19 | + |
| 20 | + // Start activities asynchronously. |
| 21 | + var helloResult, byeResult string |
| 22 | + helloFuture := workflow.ExecuteActivity(ctx, HelloActivity, name) |
| 23 | + byeFuture := workflow.ExecuteActivity(ctx, ByeActivity, name) |
| 24 | + |
| 25 | + // This can be done alternatively by creating a workflow selector. See |
| 26 | + // "pickfirst" example. |
| 27 | + err := helloFuture.Get(ctx, &helloResult) |
| 28 | + if err != nil { |
| 29 | + return "", fmt.Errorf("hello activity error: %s", err.Error()) |
| 30 | + } |
| 31 | + err = byeFuture.Get(ctx, &byeResult) |
| 32 | + if err != nil { |
| 33 | + return "", fmt.Errorf("bye activity error: %s", err.Error()) |
| 34 | + } |
| 35 | + |
| 36 | + return helloResult + "\n" + byeResult, nil |
| 37 | +} |
| 38 | + |
| 39 | +// Each of these activities will sleep for 5 seconds, but see in the temporal |
| 40 | +// dashboard that they were created immediately one after the other. |
| 41 | + |
| 42 | +func HelloActivity(ctx context.Context, name string) (string, error) { |
| 43 | + logger := activity.GetLogger(ctx) |
| 44 | + logger.Info("Hello activity", "name", name) |
| 45 | + time.Sleep(5 * time.Second) |
| 46 | + return "Hello " + name + "!", nil |
| 47 | +} |
| 48 | + |
| 49 | +func ByeActivity(ctx context.Context, name string) (string, error) { |
| 50 | + logger := activity.GetLogger(ctx) |
| 51 | + logger.Info("Bye activity", "name", name) |
| 52 | + time.Sleep(5 * time.Second) |
| 53 | + return "Bye " + name + "!", nil |
| 54 | +} |
0 commit comments