Skip to content

n8n 触发器详解 - 掌握工作流启动的艺术

触发器是工作流的起点,决定了自动化何时开始执行。选择合适的触发器类型对于构建高效的自动化系统至关重要。今天我们来深入了解 n8n 的各种触发器。

触发器分类概览

n8n 的触发器可以分为几大类:

类型特点适用场景
手动触发人工启动测试、一次性任务
时间触发按时间规律执行定期报告、数据同步
事件触发外部事件驱动实时响应、集成系统
轮询触发主动检查变化监控状态、数据更新

手动触发器

Manual Trigger

最简单的触发器,适合测试和一次性任务。

使用场景

  • 工作流开发和调试
  • 手动执行的数据处理任务
  • 临时性的自动化操作

配置要点

  • 无需特殊配置
  • 可以在执行时传入初始数据
  • 支持批量数据输入

实际应用

json
{
  "name": "Manual Data Import",
  "description": "手动导入客户数据",
  "inputData": [
    {
      "name": "张三",
      "email": "zhangsan@example.com",
      "phone": "13800138000"
    }
  ]
}

时间触发器

Cron Trigger

基于 Cron 表达式的定时触发器,功能最强大的时间触发方式。

Cron 表达式格式

* * * * * *
│ │ │ │ │ │
│ │ │ │ │ └── 年份 (可选)
│ │ │ │ └──── 星期 (0-7, 0和7都表示周日)
│ │ │ └────── 月份 (1-12)
│ │ └──────── 日期 (1-31)
│ └────────── 小时 (0-23)
└──────────── 分钟 (0-59)

常用表达式示例

bash
# 每天早上 9 点
0 9 * * *

# 工作日下午 6 点
0 18 * * 1-5

# 每周一早上 8 点
0 8 * * 1

# 每月 1 号凌晨 2 点
0 2 1 * *

# 每 15 分钟执行一次
*/15 * * * *

# 每小时的第 30 分钟
30 * * * *

高级配置

json
{
  "cronExpression": "0 9 * * 1-5",
  "timezone": "Asia/Shanghai",
  "triggerAtStartup": false
}

Interval Trigger

简单的间隔触发器,适合规律性的重复任务。

配置选项

  • 间隔时间:秒、分钟、小时
  • 执行次数限制
  • 启动延迟

使用示例

json
{
  "interval": 300,  // 5分钟
  "unit": "seconds",
  "limit": 100      // 最多执行100次
}

适用场景

  • 简单的定期检查
  • 数据同步任务
  • 健康检查

事件触发器

Webhook Trigger

通过 HTTP 请求触发工作流,是最灵活的触发方式。

基础配置

json
{
  "httpMethod": "POST",
  "path": "webhook-path",
  "authentication": "none",
  "responseMode": "onReceived"
}

安全配置

json
{
  "authentication": "basicAuth",
  "basicAuth": {
    "user": "webhook_user",
    "password": "secure_password"
  }
}

实际应用案例

1. GitHub Webhook 集成

bash
# GitHub 仓库设置中添加 Webhook
URL: https://your-n8n.com/webhook/github-deploy
Content type: application/json
Events: push, pull_request

工作流处理:

javascript
// 在 Code 节点中处理 GitHub 数据
const payload = items[0].json;
const eventType = payload.headers['x-github-event'];
const repository = payload.body.repository.name;
const branch = payload.body.ref.split('/').pop();

return [{
  json: {
    event: eventType,
    repo: repository,
    branch: branch,
    timestamp: new Date().toISOString()
  }
}];

2. 支付回调处理

javascript
// 处理支付平台回调
const paymentData = items[0].json.body;

// 验证签名
const signature = items[0].json.headers['x-signature'];
const isValid = verifySignature(paymentData, signature);

if (!isValid) {
  throw new Error('Invalid signature');
}

return [{
  json: {
    orderId: paymentData.order_id,
    status: paymentData.status,
    amount: paymentData.amount,
    verified: true
  }
}];

Email Trigger

监控邮箱,收到邮件时触发工作流。

IMAP 配置

json
{
  "host": "imap.gmail.com",
  "port": 993,
  "secure": true,
  "user": "your-email@gmail.com",
  "password": "app-password"
}

过滤条件

json
{
  "filters": {
    "subject": "订单确认",
    "from": "orders@company.com",
    "hasAttachment": true
  }
}

处理邮件内容

javascript
// 提取邮件信息
const email = items[0].json;
const subject = email.subject;
const from = email.from.text;
const body = email.text;

// 解析订单号
const orderMatch = subject.match(/订单号:(\w+)/);
const orderId = orderMatch ? orderMatch[1] : null;

return [{
  json: {
    orderId,
    customerEmail: from,
    emailBody: body,
    receivedAt: new Date().toISOString()
  }
}];

轮询触发器

File Trigger

监控文件系统变化,文件新增或修改时触发。

配置示例

json
{
  "path": "/data/uploads",
  "watchFor": "added",
  "fileExtensions": ["csv", "xlsx"],
  "recursive": true
}

处理文件

javascript
// 处理新增的文件
const fileInfo = items[0].json;
const fileName = fileInfo.name;
const filePath = fileInfo.path;

// 根据文件类型处理
let processor = '';
if (fileName.endsWith('.csv')) {
  processor = 'csv-import';
} else if (fileName.endsWith('.xlsx')) {
  processor = 'excel-import';
}

return [{
  json: {
    file: fileName,
    path: filePath,
    processor: processor,
    size: fileInfo.size
  }
}];

RSS Trigger

监控 RSS 源,有新内容时触发。

配置

json
{
  "url": "https://blog.example.com/rss.xml",
  "pollInterval": 300  // 5分钟检查一次
}

内容处理

javascript
// 处理 RSS 新文章
const rssItem = items[0].json;
const title = rssItem.title;
const link = rssItem.link;
const pubDate = new Date(rssItem.pubDate);

// 检查是否为今天发布
const today = new Date();
const isToday = pubDate.toDateString() === today.toDateString();

return [{
  json: {
    title,
    link,
    publishDate: pubDate.toISOString(),
    isNewToday: isToday
  }
}];

高级触发器配置

错误处理

重试机制

json
{
  "retryOnFail": true,
  "retryTimes": 3,
  "retryInterval": 1000
}

错误通知

javascript
// 在 Error Trigger 中处理失败
const error = items[0].json;
const workflowName = error.workflow.name;
const errorMessage = error.error.message;

// 发送错误通知
return [{
  json: {
    alert: 'Workflow Failed',
    workflow: workflowName,
    error: errorMessage,
    timestamp: new Date().toISOString()
  }
}];

条件触发

基于数据的条件触发

javascript
// 在触发器后添加 IF 节点
const data = items[0].json;
const shouldProcess = data.priority === 'high' || data.amount > 1000;

return [{
  json: {
    ...data,
    shouldProcess
  }
}];

批量处理

Split In Batches 配合触发器

json
{
  "batchSize": 10,
  "options": {
    "reset": false
  }
}

触发器选择指南

根据场景选择

实时响应需求

  • Webhook Trigger:外部系统集成
  • Email Trigger:邮件自动处理
  • File Trigger:文件监控

定时任务需求

  • Cron Trigger:复杂时间规律
  • Interval Trigger:简单间隔重复

手动控制需求

  • Manual Trigger:测试和一次性任务

性能考虑

轮询频率

  • 避免过于频繁的轮询
  • 根据业务需求调整检查间隔
  • 考虑系统资源消耗

并发控制

  • 设置合理的执行限制
  • 避免同一工作流并发执行冲突
  • 使用队列机制处理高并发

实战案例:多触发器工作流

客户服务自动化系统

需求

  • 邮件触发:处理客户咨询
  • Webhook 触发:处理在线表单
  • 定时触发:发送每日报告

架构设计

Email Trigger → 邮件处理分支

Webhook Trigger → 表单处理分支  → 合并处理 → 客服分配

Cron Trigger → 报告生成分支

实现要点

  1. 使用不同的触发器处理不同来源
  2. 通过 Merge 节点统一处理流程
  3. 添加条件判断区分处理逻辑

小结

触发器是工作流自动化的核心,选择合适的触发器类型能够:

  1. 提高效率:自动响应事件,减少人工干预
  2. 保证及时性:实时处理重要业务事件
  3. 降低成本:减少系统资源消耗
  4. 提升可靠性:稳定的触发机制保证业务连续性

下一篇文章,我们将学习数据处理和转换技术,这是构建复杂工作流的另一个重要环节。

记住,好的触发器设计是成功自动化的第一步。花时间理解业务需求,选择最适合的触发方式,会让后续的工作流开发事半功倍。