探索活动
GitHub Actions 工作流由 事件 触发 - 存储库或计划内发生的特定活动。 事件由 on 工作流定义中的子句定义,并确定自动化何时运行。
计划事件
使用 cron 语法计划在特定时间运行的工作流。 这非常适合维护任务、定期报告或夜间生成。
on:
schedule:
# Runs every weekday at 8 AM UTC
- cron: "0 8 * * 1-5"
# Runs every Sunday at midnight UTC
- cron: "0 0 * * 0"
Cron 语法明细:
- 分钟 (0-59) | 小时 (0-23) | Day (1-31) | 月份 (1-12) | 工作日 (0-6, 星期日=0)
- 使用月份名称:
JAN-DEC和日名称:SUN-SAT - 使用
*表示“any”(在 YAML 中引用 cron 字符串)
示例:
-
'0 9-17 * * 1-5'每小时从上午 9 点到下午 5 点,星期一到星期五 -
'30 2 * * *'- 每日凌晨 2:30 -
'0 0 1 * *'- 每月第一天午夜
代码存储库事件
最常见的触发器响应存储库中的代码更改:
基本推送和拉取请求事件
on:
# Single event
push
# Multiple events
pull_request
# Or as a list
on: [push, pull_request]
包含分支和路径的筛选事件
on:
push:
branches: [main, develop]
paths: ["src/**", "!docs/**"]
pull_request:
branches: [main]
types: [opened, synchronize, reopened]
常见存储库事件
| 事件 | Trigger | 用例 |
|---|---|---|
push |
代码推送到分支 | CI/CD,自动测试 |
pull_request |
PR 已打开/更新 | 代码评审自动化 |
release |
已发布版本 | 部署到生产环境 |
create |
已创建的分支或标记 | 初始化环境 |
delete |
已删除分支/标记 | 清理资源 |
手动事件
使用 workflow_dispatch以下命令从 GitHub Actions 选项卡手动触发工作流:
on:
workflow_dispatch:
inputs:
environment:
description: "Deployment environment"
required: true
default: "staging"
type: choice
options:
- staging
- production
version:
description: "Version to deploy"
required: true
type: string
注释
工作流文件必须存在于默认分支中,才能在手动触发器 UI 中显示。
Webhook 事件
GitHub 为存储库活动提供了许多 Webhook 事件:
on:
# Wiki page created or updated
gollum
# Issues opened, closed, or edited
issues:
types: [opened, edited, closed]
# New release published
release:
types: [published]
外部事件
用于 repository_dispatch 通过 GitHub 的 REST API 从外部系统触发工作流:
on:
repository_dispatch:
types: [deploy-staging, run-tests]
外部触发机制:
curl -X POST \
-H "Authorization: token YOUR_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/OWNER/REPO/dispatches \
-d '{"event_type":"deploy-staging","client_payload":{"environment":"staging"}}'
活动的最佳实践
- 具体来说:使用分支和路径筛选器以避免不必要的运行
- 合并相关事件:在一个工作流中对类似的触发器进行分组
- 使用适当的事件类型:根据需要选择最具体的事件类型
-
手动测试首先:在开发中使用
workflow_dispatch - 监视使用情况:查看工作流运行以优化事件配置
有关完整的事件文档,请参阅 触发工作流的事件。