# Wait / Delay

> 将执行流暂停指定时长，或暂停到某个特定时间戳。

Source: https://docs.sommatic.ai/zh/nodes/flow.wait/

- 标识: `flow.wait`
- 类别: 流程控制
- 版本: 1.0.0
- 状态: 部分可用. `duration` 模式会真正暂停运行，最长 10 秒；`timestamp` 模式不会等待，会立即经 `out` 继续。
- 执行方式: async

将执行流暂停指定时长，或暂停到某个特定时间戳。

该算子用于引入延迟，或将执行安排在未来某个时间。它依赖编排引擎挂起工作流，并在计算出的唤醒时间恢复执行。

**模式：**
- **Duration：** 等待一段相对时间（例如“5 分钟”）。
- **Timestamp：** 等待到某个绝对日期/时间（例如“2025-12-31T23:59:59Z”）。

**适用场景：**
- 在用户注册 24 小时后发送跟进邮件。
- 等待连接重试的退避时间。
- 将工作流暂停到某个特定业务日期。

## 配置

- `type` (string, 可选): 默认值: `duration`. 可选值: `duration`, `timestamp`.
- `duration_seconds` (integer, 可选): 等待的秒数（Type 为“duration”时使用）。 默认值: `60`.
- `timestamp_expr` (string, 可选, 支持表达式): ISO-8601 时间戳，或结果为时间戳的表达式（Type 为“timestamp”时使用）。

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `out` (默认): 延迟结束后从此处恢复执行。
- `error`: 时间戳无效时激活。

## 输入契约

- `payload` (object, 可选)

## 输出契约

- `payload` (object, 可选)

## 在表达式中

后续节点可通过 `$("Wait / Delay").item.json.<路径>` 读取此节点输出中的内容（请把 `Wait / Delay` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Wait / Delay").item.json.payload` (object) **worker 不返回：读取结果为 undefined.**
- `$("Wait / Delay").item.json.ticket_id` (string) = `"tk_9"` (编辑器不提示)
- `$("Wait / Delay").item.json.due_at` (string) = `"2026-12-01T09:00:00Z"` (编辑器不提示)


## 工作原理

实验性。`duration` 模式下会真实休眠（最多 10 秒）后继续；`timestamp` 模式下只计算恢复时间并立即继续。工作流从不会被挂起。

1. 解析配置；`type` 默认为 `duration`。缺少 `duration_seconds` 时代码使用 0，而非 schema 默认的 60。
2. `duration`：将 `resume_at` 设为当前时间加 `duration_seconds`，并在 worker 内休眠 `min(duration, 10 秒)`。
3. `timestamp`：若原始 `timestamp_expr` 包含 `{{`，使用解析后的值；否则作为 JSONata 针对 payload 求值（`due_at`）。用 `new Date()` 解析并计算 `delay_ms`。不会休眠。
4. 通过 `out` 原样返回 payload，并带 `meta` `{ action: "suspend", resume_at, delay_ms }`。引擎忽略 `meta.action`，立即执行下一个节点。

## 在工作流中

### 节点

```json
{
  "node_id": "node-wait-due",
  "label": "Wait until due",
  "operator_slug": "flow.wait",
  "operator_version": "1.0.0",
  "config": {
    "type": "timestamp",
    "timestamp_expr": "{{ $json.due_at }}"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "ticket_id": "tk_9",
    "due_at": "2026-12-01T09:00:00Z"
  },
  "port": "out",
  "meta": {
    "action": "suspend",
    "resume_at": "2026-12-01T09:00:00.000Z",
    "delay_ms": 410400000
  }
}
```

## 输出端口 (代码中的行为)

### `out`

在限时休眠后（`duration`）或立即（`timestamp`）。

```json
{
  "ticket_id": "tk_9",
  "due_at": "2026-12-01T09:00:00Z"
}
```

### `error`

仅在 worker 意外抛错时；无效时间戳会从 `out` 输出（见错误）。

```json
{
  "error": "<message>"
}
```

## 代码中的行为

- `timestamp_expr`: 可使用 `{{ $json.due_at }}`、JSONata 路径（如 `due_at`）或加引号的字面量 `"2026-12-01T09:00:00Z"`。未设置 `timestamp_expr` 时，`timestamp` 模式返回 `resume_at: null` 和 `delay_ms: 0`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Wait timestamp error: <message>` | `out` | `timestamp_expr` 不是有效日期，或是未加 `{{ }}` 或引号的 ISO 字符串（JSONata 无法解析 `2026-12-01T09:00:00Z`）。信封没有端口，引擎将其路由到 `out`，下一个节点收到的 payload 是 `{ ok: false, errors: [...] }`。 |

## 说明与限制

- 没有持久化定时器：超过 10 秒的等待会被截断为 10 秒，节点休眠期间会占住当前运行。
- `meta` 只记录在运行步骤中：下游节点收到的 payload 是 `data`，无法通过 `$json` 或 `$("Node")` 读取 `meta`。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "flow.wait",
  "name": "Wait / Delay",
  "category": "flow",
  "version": "1.0.0",
  "description": "Pauses the execution flow for a specified duration or until a specific timestamp.\n\n  This operator is used to introduce delays or schedule execution for a future time. It relies on the orchestration engine to suspend the workflow and resume it at the calculated wake-up time.\n\n  **Modes:**\n  - **Duration:** Waits for a relative amount of time (e.g., \"5 minutes\").\n  - **Timestamp:** Waits until a specific absolute date/time (e.g., \"2025-12-31T23:59:59Z\").\n\n  **Use Cases:**\n  - Sending a follow-up email 24 hours after sign-up.\n  - Waiting for a connection retry backoff.\n  - Pausing a workflow until a specific business date.",
  "capabilities": [
    "delay",
    "schedule",
    "time",
    "suspend"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "type": {
        "type": "string",
        "enum": [
          "duration",
          "timestamp"
        ],
        "default": "duration",
        "title": "Wait Type"
      },
      "duration_seconds": {
        "type": "integer",
        "title": "Duration (Seconds)",
        "default": 60,
        "description": "Number of seconds to wait (used when Type is \"duration\")."
      },
      "timestamp_expr": {
        "type": "string",
        "title": "Until (Timestamp)",
        "format": "expression",
        "description": "ISO-8601 Timestamp or expression evaluating to one (used when Type is \"timestamp\")."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "description": "Payload passed into the wait state.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "Payload passed out after resumption (usually unchanged).",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Resume",
      "is_default": true,
      "description": "Execution resumes here after the delay."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Activated if the timestamp is invalid."
    }
  ],
  "execution_mode": "async",
  "tags": [
    "time",
    "sleep",
    "control-flow",
    "schedule"
  ],
  "is_stateful": true,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "duration",
        "timestamp"
      ],
      "default": "duration",
      "title": "Wait Type"
    },
    "duration_seconds": {
      "type": "integer",
      "title": "Duration (Seconds)",
      "default": 60,
      "description": "Number of seconds to wait (used when Type is \"duration\")."
    },
    "timestamp_expr": {
      "type": "string",
      "title": "Until (Timestamp)",
      "format": "expression",
      "description": "ISO-8601 Timestamp or expression evaluating to one (used when Type is \"timestamp\")."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "description": "Payload passed into the wait state.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "Payload passed out after resumption (usually unchanged).",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Resume",
    "is_default": true,
    "description": "Execution resumes here after the delay."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Activated if the timestamp is invalid."
  }
]
```
