You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jenkins scripted pipeline中按星期条件触发不同stage运行?

结论

when是Jenkins声明式流水线(Declarative Pipeline)的专属语法,你当前使用的脚本式流水线(Scripted Pipeline)无法直接使用when,但两种流水线范式都可以实现按星期过滤stage执行的需求,具体实现方案如下:


方案1:继续使用现有脚本式流水线

直接在stage内通过if判断星期即可,修改后的代码如下:

import java.util.Calendar

node {
    // 获取当前星期,取值规则:周日=1、周一=2、周五=6
    def dayOfWeek = Calendar.instance.get(Calendar.DAY_OF_WEEK)
    
    stage('build on friday ') {
        if (dayOfWeek == Calendar.FRIDAY) {
            echo "Hai its friday"
        } else {
            echo "非周五,跳过当前stage"
        }
    }
        
    stage('build on sunday') {
        if (dayOfWeek == Calendar.SUNDAY) {
            echo "Hai its sunday"
        } else {
            echo "非周日,跳过当前stage"
        }
    }
}

方案2:切换为声明式流水线使用when条件

如果你希望用when实现需求,可以将流水线改写为声明式范式,代码示例如下:

import java.util.Calendar

pipeline {
    agent any
    stages {
        stage('build on friday') {
            when {
                expression {
                    return Calendar.instance.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY
                }
            }
            steps {
                echo "Hai its friday"
            }
        }
        stage('build on sunday') {
            when {
                expression {
                    return Calendar.instance.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY
                }
            }
            steps {
                echo "Hai its sunday"
            }
        }
    }
}

注意事项

如果Jenkins节点的时区和你预期的时区不一致,会导致星期判断错误,你可以手动指定时区获取时间:

def dayOfWeek = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai")).get(Calendar.DAY_OF_WEEK)

内容的提问来源于stack exchange,提问作者Srikanth k SOF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 15:15:04