|
| 1 | +--- |
| 2 | +layout: default |
| 3 | +title: Sleep |
| 4 | +permalink: /docs/go-client/sleep |
| 5 | +--- |
| 6 | + |
| 7 | +# Workflow Sleep |
| 8 | + |
| 9 | +The `workflow.Sleep` function allows a Cadence workflow to pause its execution for a specified duration. This is similar to `time.Sleep` in Go, but is safe and deterministic for use within Cadence workflows. The workflow will be paused and resumed by the Cadence service, and the sleep is durable—meaning the workflow can survive worker restarts or failures during the sleep period. |
| 10 | + |
| 11 | +## Example: Sleep for 30 Seconds |
| 12 | + |
| 13 | +Here is a minimal example of using `workflow.Sleep` in a Cadence workflow, as demonstrated in [cadence-samples PR #99](https://github.com/cadence-workflow/cadence-samples/pull/99): |
| 14 | + |
| 15 | +```go |
| 16 | +import ( |
| 17 | + "time" |
| 18 | + "go.uber.org/cadence/workflow" |
| 19 | +) |
| 20 | + |
| 21 | +func SleepWorkflow(ctx workflow.Context) error { |
| 22 | + workflow.GetLogger(ctx).Info("Workflow started, going to sleep for 30 seconds...") |
| 23 | + err := workflow.Sleep(ctx, 30*time.Second) |
| 24 | + if err != nil { |
| 25 | + workflow.GetLogger(ctx).Error("Sleep interrupted", "Error", err) |
| 26 | + return err |
| 27 | + } |
| 28 | + workflow.GetLogger(ctx).Info("Woke up after 30 seconds!") |
| 29 | + return nil |
| 30 | +} |
| 31 | +``` |
| 32 | + |
| 33 | +### Key Points |
| 34 | +- Use `workflow.Sleep(ctx, duration)` instead of `time.Sleep` inside workflow code. |
| 35 | +- The sleep is durable: if the worker crashes or restarts, the workflow will resume sleeping where it left off. |
| 36 | +- The workflow is not consuming worker resources while sleeping; the state is persisted by Cadence. |
| 37 | +- You can use any duration supported by Go's `time.Duration`. |
| 38 | + |
| 39 | +### When to Use |
| 40 | +- Delaying workflow progress for a fixed period (e.g., retry with backoff, scheduled reminders, timeouts). |
| 41 | +- Waiting for an external event or timeout before proceeding. |
| 42 | + |
| 43 | +### Limitations |
| 44 | +- Do not use `time.Sleep` in workflow code; always use `workflow.Sleep` for determinism and durability. |
| 45 | +- Very large numbers of simultaneous timers (sleeps) may impact cluster performance; consider jittering or batching if needed. |
| 46 | + |
| 47 | +For more details and advanced usage, see the [Cadence Go client documentation](https://pkg.go.dev/go.uber.org/cadence/workflow#Sleep). |
0 commit comments