# Cron Schedule

> 使用 CRON 语法按精确的计划启动工作流执行。

Source: https://docs.sommatic.ai/zh/nodes/cron.trigger/

- 标识: `cron.trigger`
- 类别: 触发器
- 版本: 1.0.0
- 状态: 部分可用. 调度器仅根据分钟和小时字段估算间隔：不遵循精确时间、星期几和时区。`jitter_ms` 也不会生效。
- 执行方式: async

使用 CRON 语法按精确的计划启动工作流执行。

该触发器是基于时间的自动化入口。它支持标准 CRON 表达式来定义周期性间隔（例如“每周五下午 5 点”）。

**功能特性：**
- **标准 Cron：** 完整支持“* * * * *”语法。
- **时区：** 调度遵循本地化时区。
- **抖动：** 可选的随机延迟，用于避免“惊群”问题。

**适用场景：**
- 生成每日报表。
- 运行夜间清理任务。
- 每 15 分钟轮询一次 API。

## 配置

- `cron_expr` (string, 必填): 标准 cron（分 时 日 月 星期）。 默认值: `0 0 * * *`.
- `timezone` (string, 可选): 默认值: `UTC`.
- `payload_template` (object, 可选): 可选，注入工作流启动上下文的 JSON。

## 输出端口

- `out` (默认): 工作流已启动。
- `error`: Error

## 输出契约

- `timestamp` (string, 可选)
- `schedule_time` (string, 可选)

## 在表达式中

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

- `$("Cron Schedule").item.json.timestamp` (string) = `"2026-11-26T00:00:03.120-05:00"`
- `$("Cron Schedule").item.json.schedule_time` (string) **worker 不返回：读取结果为 undefined.**
- `$("Cron Schedule").item.json.$scheduled` (boolean) = `true` (编辑器不提示)
- `$("Cron Schedule").item.json.$trigger_state` (object) = `{…}` (编辑器不提示)
- `$("Cron Schedule").item.json.$trigger_state.lastExecutedAt` (string) = `"2026-11-25T05:00:02.311Z"` (编辑器不提示)
- `$("Cron Schedule").item.json.report` (string) = `"daily-sales"` (编辑器不提示)
- `$("Cron Schedule").item.json.schedule` (string) = `"0 0 * * *"` (编辑器不提示)
- `$("Cron Schedule").item.json.timezone` (string) = `"America/New_York"` (编辑器不提示)


## 工作原理

计划工作流的入口节点。后端调度器启动运行后，本节点输出合并了 `payload_template` 的输入数据，并附加 `timestamp`、`schedule` 和 `timezone`。

1. 触发来源：后端调度器每 10 秒检查一次已发布且包含本节点的活跃工作流；距上次启动已超过 `cron_expr` 的估算间隔时，启动已发布版本（若没有上次启动记录，则立即启动）。运行输入为 `{ $scheduled: true }` 加上已保存的 `$trigger_state`。
2. 间隔根据分钟和小时字段估算：`*` → 每分钟，`*/N` → 每 N 分钟，分钟固定且小时为 `*` → 每小时，其他情况 → 每天。不会匹配确切时间，也不会处理星期和日期字段。
3. 节点运行时解析配置（`cron_expr` 默认 `0 0 * * *`，`timezone` 默认 `UTC`，`payload_template` 默认 `{}`），并获取 `timezone` 时区下的当前时间。
4. 经 `out` 输出 `{ ...input, ...payload_template, timestamp, schedule, timezone }`，并附带 `meta: { triggered_at, jitter_applied }`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-nightly",
  "label": "Every night",
  "operator_slug": "cron.trigger",
  "operator_version": "1.0.0",
  "config": {
    "cron_expr": "0 0 * * *",
    "timezone": "America/New_York",
    "payload_template": {
      "report": "daily-sales"
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "$scheduled": true,
    "$trigger_state": {
      "lastExecutedAt": "2026-11-25T05:00:02.311Z"
    },
    "report": "daily-sales",
    "timestamp": "2026-11-26T00:00:03.120-05:00",
    "schedule": "0 0 * * *",
    "timezone": "America/New_York"
  },
  "port": "out",
  "meta": {
    "triggered_at": "2026-11-26T00:00:03.120-05:00",
    "jitter_applied": 0
  }
}
```

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

### `out`

总是从此端口输出。`$scheduled` 和 `$trigger_state` 来自调度器的输入；手动运行时只有你提供的输入。

```json
{
  "$scheduled": true,
  "$trigger_state": {
    "lastExecutedAt": "2026-11-25T05:00:02.311Z"
  },
  "report": "daily-sales",
  "timestamp": "2026-11-26T00:00:03.120-05:00",
  "schedule": "0 0 * * *",
  "timezone": "America/New_York"
}
```

### `error`

已声明，但代码从不输出到此端口。

## 代码中的行为

- `cron_expr`: 节点不会校验该表达式。调度器只从中推导一个间隔（见运行流程），因此 `0 9 * * 1-5` 会从上次启动起每天运行一次，而不是在工作日 09:00 运行。
- `timezone`: 只影响 `timestamp` 和 `meta.triggered_at` 的格式，不影响调度器的启动时间。时区名称无效时 `timestamp` 为 `null`。
- `payload_template`: 其键会覆盖输入中的同名键；`timestamp`、`schedule`、`timezone` 总会覆盖模板中的同名键。
- `jitter_ms`: 会被读取但未声明，也不会生效：不会增加任何延迟，只是原样回显在 `meta.jitter_applied` 中。

## 说明与限制

- 测试与生产：调度器只启动已发布版本，草稿不会自行运行。手动运行会立即执行本节点，不带 `$scheduled`。使用示例数据时，引擎会跳过本节点并经 `out` 输出示例输入。
- 调度器从工作流草稿读取触发器配置，但运行的是已发布版本。
- 输出契约中列出的 `schedule_time` 从不会生成。


## 契约（JSON Schema）

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

```json
{
  "slug": "cron.trigger",
  "name": "Cron Schedule",
  "category": "triggers",
  "version": "1.0.0",
  "description": "Initiates workflow execution on a precise schedule using CRON syntax.\n\n  This trigger is the entry point for time-based automation. It supports standard CRON expressions for defining recurring intervals (e.g., \"Every Friday at 5 PM\").\n\n  **Features:**\n  - **Standard Cron:** Full support for \"* * * * *\" syntax.\n  - **Timezones:** Schedule respects localized time zones.\n  - **Jitter:** Optional random delay to prevent \"thundering herd\" issues.\n\n  **Use Cases:**\n  - Generating daily reports.\n  - Running nightly cleanup jobs.\n  - Polling an API every 15 minutes.",
  "capabilities": [
    "scheduling",
    "time-based",
    "cron"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "cron_expr"
    ],
    "properties": {
      "cron_expr": {
        "type": "string",
        "title": "CRON Expression",
        "default": "0 0 * * *",
        "description": "Standard cron (min hour day month day-of-week)."
      },
      "timezone": {
        "type": "string",
        "default": "UTC",
        "title": "Timezone",
        "ui_widget": "timezone_picker"
      },
      "payload_template": {
        "type": "object",
        "title": "Static Payload",
        "description": "Optional JSON to inject into the workflow start context."
      }
    }
  },
  "input_contract_schema": null,
  "output_contract_schema": {
    "type": "object",
    "description": "Schedule metadata.",
    "properties": {
      "timestamp": {
        "type": "string",
        "format": "date-time"
      },
      "schedule_time": {
        "type": "string",
        "format": "date-time"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Start",
      "is_default": true,
      "description": "Workflow Started."
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "schedule",
    "time",
    "start",
    "trigger"
  ],
  "is_stateful": false,
  "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",
  "required": [
    "cron_expr"
  ],
  "properties": {
    "cron_expr": {
      "type": "string",
      "title": "CRON Expression",
      "default": "0 0 * * *",
      "description": "Standard cron (min hour day month day-of-week)."
    },
    "timezone": {
      "type": "string",
      "default": "UTC",
      "title": "Timezone",
      "ui_widget": "timezone_picker"
    },
    "payload_template": {
      "type": "object",
      "title": "Static Payload",
      "description": "Optional JSON to inject into the workflow start context."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "Schedule metadata.",
  "properties": {
    "timestamp": {
      "type": "string",
      "format": "date-time"
    },
    "schedule_time": {
      "type": "string",
      "format": "date-time"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Start",
    "is_default": true,
    "description": "Workflow Started."
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
