当您使用自由风格项目时,可以设置在20分钟后,如果尚未完成,则取消构建。如何在Jenkins多分支管道项目中实现此功能?
当您使用自由风格项目时,可以设置在20分钟后,如果尚未完成,则取消构建。如何在Jenkins多分支管道项目中实现此功能?
timeout(20) {
node {
sh 'foo'
}
}
如果您需要不同于 MINUTES 的 TimeUnit
,则可以提供 unit 参数:timeout(time: 20, unit: 'SECONDS') {
2018年8月更新:如今随着更常见的声明性流水线(可以通过顶层pipeline
结构轻松识别),超时也可以在不同级别上(每个整个流水线或每个阶段)使用选项
指定:
pipeline {
options {
timeout(time: 1, unit: 'HOURS')
}
stages { .. }
// ..
}
不过,如果你想在声明性流水线的单个步骤中应用超时,则可以按照上述描述使用。
在确定的时间限制内执行块内的代码。如果达到时间限制,将抛出异常(org.jenkinsci.plugins.workflow.steps.FlowInterruptedException),导致构建中止(除非它被捕获并进行处理)。单位是可选的,默认为分钟。
超时步骤有3个参数可以配置:
time (必需, 整数)
activity (可选, 布尔值)
unit (可选, 值: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS)
示例:
timeout(time: 10) // would lead to a timeout of 10 minutes (MINUTES is default value)
timeout(time: 10, unit: 'SECONDS') // a 10 seconds timeout
timeout(time: 10, activity: false, unit: 'MILLISECONDS')
Jenkins官方文档提供了一个非常好的超时使用示例:
pipeline {
agent any
options {
timeout(time: 1, unit: 'HOURS')
}
stages {
stage('Example') {
steps {
echo 'Hello World'
}
}
}
}
pipeline { agent any stages { stage('Example') { options { timeout(time: 1, unit: 'HOURS') } steps { echo 'Hello World' } } } }
- YashcatchError
指令。 - Max Cascone在声明式流水线中,您可以使用:
pipeline {
agent any
stages {
stage('Deploy') {
steps {
retry(3) {
sh './flakey-deploy.sh'
}
timeout(time: 3, unit: 'MINUTES') {
sh './health-check.sh'
}
}
}
}
}
对于一个声明式管道(整个作业的超时时间):
pipeline {
options {
timeout(time: 3, unit: 'HOURS')
}
agent {
label 'agent_name'
}
stages {
stage('Stage_name') {
steps {
// ...
}
}
}
// ...
}
对于一个脚本化流水线(整个作业的超时):
def call() {
node('agent_name') {
timeout(time: 3, unit: 'HOURS') {
stage('Stage_name') {
// ...
}
}
}
}
在一个阶段内的超时时间(针对特定操作):
声明性流水线
pipeline {
agent {
label 'agent_name'
}
stages {
stage('Stage_name') {
steps {
timeout(time: 3, unit: 'HOURS') {
sh ' ... '
echo '...'
// ...
}
// ...
}
}
}
}
脚本化流水线
def call() {
node('agent_name') {
stage('Stage_name') {
timeout(time: 3, unit: 'HOURS') {
sh '...'
echo '...'
// ...
}
// ...
}
}
}
pipeline {
agent any
stages {
stage('Example') {
options {
timeout(time: 1, unit: 'HOURS')
}
steps {
echo 'Hello World'
}
}
}
}
NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS
ref:
https://www.jenkins.io/doc/book/pipeline/syntax/#options
https://www.jenkins.io/doc/pipeline/steps/workflow-basic-steps/#timeout-enforce-time-limit
JENKINS_URL/job/<任何流水线项目>/pipeline-syntax/
→ 步骤参考. - Gerold BrosercatchError
指令,它是一种高级的 try/catch 结构,可以让您在捕获异常时设置自己的消息。 - Max Cascone