任务触发器 #
Jenkins提供多种构建触发方式,可以根据不同的场景选择合适的触发策略。本节将详细介绍各种触发器的配置和使用方法。
触发器类型概览 #
| 类型 | 触发方式 | 适用场景 |
|---|---|---|
| 手动触发 | 点击Build Now | 临时构建、调试 |
| 定时触发 | Cron表达式 | 定时任务、夜间构建 |
| 轮询SCM | 定期检查代码变更 | 代码提交触发 |
| 远程触发 | HTTP请求 | 外部系统集成 |
| Webhook | Git推送事件 | Git仓库集成 |
| 上游触发 | 其他任务完成 | 流水线编排 |
手动触发 #
基本操作 #
- 进入任务页面
- 点击左侧 Build Now
- 查看构建队列和执行状态
带参数构建 #
如果任务配置了参数,点击 Build with Parameters:
text
┌─────────────────────────────────────────────────────────────┐
│ Build with Parameters │
├─────────────────────────────────────────────────────────────┤
│ │
│ ENVIRONMENT │
│ ○ dev │
│ ● test │
│ ○ staging │
│ ○ prod │
│ │
│ DEPLOY │
│ ☑ 部署到测试环境 │
│ │
│ VERSION │
│ [1.0.0________________] │
│ │
│ [开始构建] │
└─────────────────────────────────────────────────────────────┘
CLI触发 #
bash
java -jar jenkins-cli.jar -s http://JENKINS_URL build my-job
java -jar jenkins-cli.jar -s http://JENKINS_URL build my-job -p ENVIRONMENT=prod
定时触发 (Build Periodically) #
Cron语法 #
text
┌───────────── 分钟 (0 - 59)
│ ┌───────────── 小时 (0 - 23)
│ │ ┌───────────── 日 (1 - 31)
│ │ │ ┌───────────── 月 (1 - 12)
│ │ │ │ ┌───────────── 星期 (0 - 6) (0是周日)
│ │ │ │ │
* * * * *
特殊字符 #
| 字符 | 说明 | 示例 |
|---|---|---|
* |
所有值 | * * * * * 每分钟 |
, |
列举值 | 0,30 * * * * 每小时的0分和30分 |
- |
范围 | 0 9-17 * * * 9点到17点每小时 |
/ |
步长 | H/15 * * * * 每15分钟 |
H |
自动分散 | H * * * * 自动分散到某分钟 |
常用示例 #
text
H * * * * 每小时(自动分散分钟)
H/15 * * * * 每15分钟
H 2 * * * 每天凌晨2点
H 2 * * 1-5 工作日凌晨2点
H 9-17 * * 1-5 工作时间每小时
H 0 1 * * 每月1号午夜
H 23 * * 1 每周一晚上11点
0 0,12 * * * 每天午夜和中午
0 0 1 1 * 每年1月1日午夜
配置示例 #
text
☑ Build periodically
Schedule: H 2 * * *
轮询SCM (Poll SCM) #
工作原理 #
text
┌─────────────────────────────────────────────────────────────┐
│ 轮询SCM流程 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 定时检查 ────► 有变更? ────► 是 ────► 触发构建 │
│ │ │ │
│ │ └──► 否 ────► 等待下次检查 │
│ │ │
│ └──────────────────────────────────────────────────────┤
│ │
└─────────────────────────────────────────────────────────────┘
配置示例 #
text
☑ Poll SCM
Schedule: H/5 * * * *
Ignore post-commit hooks: ☐
注意事项 #
text
优点:
✓ 不需要配置Webhook
✓ 适用于无法访问Jenkins的Git服务器
缺点:
✗ 产生不必要的轮询请求
✗ 响应延迟(最多等待轮询间隔)
✗ 增加Git服务器负载
远程触发 #
配置 #
text
☑ Trigger builds remotely
Authentication Token: my-build-token
触发URL #
text
# 无参数触发
http://JENKINS_URL/job/my-job/build?token=my-build-token
# 带参数触发
http://JENKINS_URL/job/my-job/buildWithParameters?token=my-build-token&ENVIRONMENT=prod
# 等待构建完成
http://JENKINS_URL/job/my-job/buildWithParameters?token=my-build-token&delay=0sec
使用curl触发 #
bash
# 基本触发
curl -X POST http://JENKINS_URL/job/my-job/build?token=my-build-token
# 带认证触发
curl -X POST \
-u username:api-token \
http://JENKINS_URL/job/my-job/build?token=my-build-token
# 带参数触发
curl -X POST \
-u username:api-token \
"http://JENKINS_URL/job/my-job/buildWithParameters?token=my-build-token&ENVIRONMENT=prod"
# 获取构建队列信息
curl -s http://JENKINS_URL/queue/api/json
使用Python触发 #
python
import requests
from requests.auth import HTTPBasicAuth
JENKINS_URL = 'http://jenkins.example.com'
JOB_NAME = 'my-job'
TOKEN = 'my-build-token'
USERNAME = 'admin'
API_TOKEN = 'your-api-token'
def trigger_build(params=None):
url = f"{JENKINS_URL}/job/{JOB_NAME}/buildWithParameters"
auth = HTTPBasicAuth(USERNAME, API_TOKEN)
response = requests.post(
url,
params={'token': TOKEN, **(params or {})},
auth=auth
)
if response.status_code == 201:
print("构建已触发")
queue_url = response.headers['Location']
return queue_url
else:
print(f"触发失败: {response.status_code}")
return None
trigger_build({'ENVIRONMENT': 'prod', 'VERSION': '1.0.0'})
Webhook触发 #
GitHub Webhook #
Jenkins配置 #
text
☑ GitHub hook trigger for GITScm polling
GitHub配置 #
- 进入GitHub仓库 → Settings → Webhooks
- 添加Webhook:
- Payload URL:
http://JENKINS_URL/github-webhook/ - Content type:
application/json - Secret: 可选
- Events: 选择触发事件
- Payload URL:
触发事件 #
text
☑ Push
☑ Pull request
☐ Commit comments
☐ Releases
GitLab Webhook #
Jenkins配置 #
text
☑ Build when a change is pushed to GitLab
Events:
☑ Push Events
☑ Merge Request Events
☐ Tag Push Events
☐ Note Events
☐ Pipeline Events
☐ Wiki Page Events
Secret token: gitlab-webhook-token
GitLab配置 #
- 进入GitLab项目 → Settings → Webhooks
- 添加Webhook:
- URL:
http://JENKINS_URL/project/my-job - Secret Token: 配置的token
- Trigger: 选择触发事件
- URL:
GitLab触发URL #
text
Push Events: http://JENKINS_URL/project/my-job
Merge Requests: http://JENKINS_URL/project/my-job
Tag Push Events: http://JENKINS_URL/project/my-job
Bitbucket Webhook #
Jenkins配置 #
text
☑ Build when a change is pushed to BitBucket
Bitbucket配置 #
- 进入仓库 → Settings → Webhooks
- 添加Webhook:
- Title: Jenkins
- URL:
http://JENKINS_URL/bitbucket-hook/
上游任务触发 #
配置 #
text
☑ Build after other projects are built
Projects to watch: upstream-job, another-job
Trigger only if build is:
● stable (成功)
○ unstable or better (不稳定或更好)
○ failed or better (失败或更好)
触发条件 #
text
┌─────────────────────────────────────────────────────────────┐
│ 上游任务状态 │ stable │ unstable │ failed │ aborted│
├─────────────────────────────────────────────────────────────┤
│ stable │ ✓ │ - │ - │ - │
│ unstable or better │ ✓ │ ✓ │ - │ - │
│ failed or better │ ✓ │ ✓ │ ✓ │ - │
└─────────────────────────────────────────────────────────────┘
Pipeline触发器 #
定时触发 #
groovy
pipeline {
agent any
triggers {
cron('H 2 * * *')
}
stages {
stage('Build') {
steps {
echo 'Nightly build...'
}
}
}
}
轮询SCM #
groovy
pipeline {
agent any
triggers {
pollSCM('H/5 * * * *')
}
stages {
stage('Build') {
steps {
echo 'Building after SCM change...'
}
}
}
}
GitHub触发 #
groovy
pipeline {
agent any
triggers {
githubPush()
}
stages {
stage('Build') {
steps {
echo 'Building after GitHub push...'
}
}
}
}
GitLab触发 #
groovy
pipeline {
agent any
triggers {
gitlab(
triggerOnPush: true,
triggerOnMergeRequest: true,
branchFilterType: 'All'
)
}
stages {
stage('Build') {
steps {
echo 'Building after GitLab event...'
}
}
}
}
定时 + 参数 #
groovy
pipeline {
agent any
triggers {
cron('H 2 * * *')
}
parameters {
choice(name: 'ENVIRONMENT', choices: ['dev', 'test', 'prod'])
booleanParam(name: 'DEPLOY', defaultValue: true)
}
stages {
stage('Build') {
steps {
echo "Building for ${params.ENVIRONMENT}"
}
}
}
}
多触发器组合 #
groovy
pipeline {
agent any
triggers {
cron('H 2 * * *')
pollSCM('H/5 * * * *')
githubPush()
}
stages {
stage('Build') {
steps {
script {
def cause = currentBuild.getBuildCauses()[0]
echo "Triggered by: ${cause.shortDescription}"
}
}
}
}
}
获取触发原因 #
groovy
pipeline {
agent any
stages {
stage('Check Trigger') {
steps {
script {
def causes = currentBuild.getBuildCauses()
causes.each { cause ->
echo "Cause: ${cause.shortDescription}"
echo "Type: ${cause._class}"
}
if (currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')) {
echo "手动触发"
}
if (currentBuild.getBuildCauses('hudson.triggers.TimerTrigger$TimerTriggerCause')) {
echo "定时触发"
}
if (currentBuild.getBuildCauses('hudson.triggers.SCMTrigger$SCMTriggerCause')) {
echo "SCM触发"
}
}
}
}
}
}
触发器最佳实践 #
1. 使用H分散负载 #
text
Good: H 2 * * *
Bad: 0 2 * * * (所有任务都在同一分钟触发)
2. 合理设置轮询间隔 #
text
Good: H/5 * * * * (5分钟)
Bad: * * * * * (每分钟,负载过高)
3. 优先使用Webhook #
text
Webhook > Poll SCM
(实时性更好,负载更低)
4. 组合使用触发器 #
groovy
triggers {
cron('H 2 * * *') // 夜间构建
githubPush() // 代码推送触发
}
5. 根据触发原因执行不同逻辑 #
groovy
stage('Deploy') {
when {
expression {
def cause = currentBuild.getBuildCauses()[0]
return cause._class.contains('UserIdCause') ||
cause._class.contains('TimerTriggerCause')
}
}
steps {
echo 'Deploying...'
}
}
下一步学习 #
小结 #
- 手动触发适合调试和临时构建
- 定时触发适合周期性任务
- 轮询SCM适合无法配置Webhook的场景
- Webhook是最推荐的代码触发方式
- 上游触发用于构建流水线编排
- 可以组合多种触发器
最后更新:2026-03-28