我如何确定当前的 Jenkins 构建是否是触发器当天的第一个 运行

How can I find out if current Jenkins build is first run of the day from trigger

我有每天触发两次的 Jenkins 作业,我想知道当前构建是否是当天的第一个 cron 触发器并执行一些操作。

我的 cron 作业如下

 triggers {
    // regression --> 3:00GMT, 14:00GMT
    cron("00 3 * * 1-5 \n 00 14 * * 1-5")
}

我可以在我的 Jenkins 文件中设置一些布尔参数来检查它是否是当天的第一个触发器吗?

最简单的选择是检查构建历史。如果前一个构建是在前一天执行的,那么当前构建就是当天的第一个构建。必须在执行的作业配置中定义逻辑。

currentBuild 对象是 org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper class 的一个实例,它提供了所有必要的信息。

steps {
    echo "The first build of the day started by trigger: ${isFirstBuildOfDayStartedByTrigger(currentBuild)}"
}

// ...

boolean isFirstBuildOfDayStartedByTrigger(currentBuild) {
    if (isStartedByTrigger(currentBuild)) {
        return false
    }
    def today = toLocalDate(currentBuild.startTimeInMillis)
    def build = currentBuild.previousBuild
    while(build != null) {
        if (toLocalDate(build.startTimeInMillis).isBefore(today)) {
            return true
        }
        if (isStartedByTrigger(build)) {
            return false
        }
        build = build.previousBuild  
    }
    return true
}

LocalDate toLocalDate(long millis) {
    return Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDate()
}

boolean isStartedByTrigger(build) {
    // TODO: use build.buildCauses or build.getBuildCauses('cause.class.Name')
    // to analyze if the job was started by trigger
    return true // or false
}

你要弄清楚触发器启动作业时添加了哪个构建原因。

如果您只是想查找当天由任何人或任何人执行的第一个构建,那么代码就简单得多:

steps {
    echo "The first build of the day: ${isFirstBuildOfDay(currentBuild)}"
}

boolean isFirstBuildOfDay(currentBuild) {
    def today = toLocalDate(currentBuild.startTimeInMillis)
    def previousBuild = currentBuild.previousBuild
    return previousBuild == null || toLocalDate(previousBuild.startTimeInMillis).isBefore(today)
}

LocalDate toLocalDate(long millis) {
    return Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDate()
}

我使用了新日期API,我认为它没有被列入白名单,所以你必须将该代码放入 Jenkins 库或批准使用的方法签名。

找到了答案,它很简单,但对我来说效果很好。 首先,我要检查这是否是预定作业,并且当前时间是否小于 5(预定作业在 5 点之前运行)

def isItFirstScheduledJob = (params.JOB_IS_SCHEDULED && new Date().getHours() < 5) ? true : false