groovy 我如何才能知道当前的Jenkins构建是否是触发器当天的第一次运行

au9on6nz  于 9个月前  发布在  Jenkins
关注(0)|答案(3)|浏览(165)

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

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

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

icnyk63a

icnyk63a1#

最简单的选择是检查生成历史记录。如果前一个生成是在前一天执行的,则当前生成是当天的第一个生成。必须在执行的作业配置中定义逻辑。
currentBuild对象是org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper类的一个示例,它提供了所有必要的信息。

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库中,或者批准使用的方法签名。

m528fe3b

m528fe3b2#

找到了答案,它很简单,但对我来说工作正常。首先,我检查这是否是一个预定的工作或没有和当前小时小于5(预定的工作运行之前5)

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

字符串

wpcxdonn

wpcxdonn3#

我在另一个例子中找到了这个答案:
https://stackoverflow.com/a/75134410/1279002
第一个月
使用方式如下:

stage('My stage')
{
    when { expression { isTriggeredByCron } }

    steps
    {
        ...
    }
}

字符串

相关问题