我的 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类的实例,它提供了所有必要的信息。
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
我在替代方案中找到了这个答案:
https://stackoverflow.com/a/75134410/1279002
isTriggeredByCron = currentBuild.getBuildCauses('hudson.triggers.TimerTrigger$TimerTriggerCause')
这样使用:
stage('My stage')
{
when { expression { isTriggeredByCron } }
steps
{
...
}
}