如何显示在Jenkins中运行构建所花费的时间?

Ita*_*not 7 build jenkins jenkins-pipeline

我正在使用Jenkins管道配置Android应用程序构建过程.

在构建的开始和结束时,将消息发送到相关的Slack通道.

Jenkinsfile的相关部分如下所示:

slackSend (channel: '#slack-test', color: 'warning', message: "Finished: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' State: ${STATE}.   Artifacts can be viewed here: ${env.BUILD_URL}artifact/Product/build/outputs/ ")
Run Code Online (Sandbox Code Playgroud)

除了上述信息之外,我还想包括构建运行到该消息所花费的时间,该消息通知构建的结束.

是否可以不添加任何外部插件?如果有一个环境变量保存这些信息,那将是完美的,但我找不到这样的变量.

小智 6

您可以使用${currentBuild.durationString}将其格式化为人类可读的格式(n 分 n 秒)。然而,它会以and countingwhich 为前缀,这有点奇怪。

所以我跟着这个 ${currentBuild.durationString.replace(' and counting', '')}


Vad*_*tov 5

您可以使用它${currentBuild.durationString}来获取构建持续时间.我在我的声明性管道脚本中使用它.

注意:如果您正在使用HipChat插件,则可以在命令中使用${BUILD_DURATION}(先前${DURATION})变量hipchatSend(它由插件传播,带有一些其他变量).

例:

post {
  success {
    hipchatSend color: 'GREEN', room: 'My room', failOnError: true, notify: false, 
      message: 'Build <a href=\'${BUILD_URL}\'>${JOB_DISPLAY_NAME} #${BUILD_NUMBER}</a> has been built. Took ${BUILD_DURATION}. See the <a href=\'${BUILD_URL}/console\'>output</a>.'
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是可以在作业配置中使用的Jenkins环境变量的更多信息.

  • @EightyEight我担心它特定于[HipChat插件](https://wiki.jenkins.io/display/JENKINS/HipChat+Plugin).我已将`$ {currentBuild.durationString}`用于其他类型的任务.我想我应该在我的回答中反映这一点. (3认同)
  • 如果您需要在数字上使用${currentBuild.duration},将以毫秒为单位返回。 (3认同)

alb*_*iff 3

由于此jenkins-pipeline脚本位于Groovy中,因此您可以简单地使用new Date()它。像这样的"Current time ${new Date()}"论证message一定有效:

slackSend (channel: '#slack-test', color: 'warning', message: "Current time ${new Date()}")
Run Code Online (Sandbox Code Playgroud)

这将在您的频道中产生以下消息:

Current time: Thu Oct 13 17:25:12 CEST 2016
Run Code Online (Sandbox Code Playgroud)

如果您想要特定的日期格式,可以使用format(String format)方法,例如"${new Date().format('dd/MM/yyyy')}"

slackSend (channel: '#slack-test', color: 'warning', message: "Current time ${new Date().format('dd/MM/yyyy')}")
Run Code Online (Sandbox Code Playgroud)

相反,这将产生以下消息:

Current time: 13/10/2016
Run Code Online (Sandbox Code Playgroud)

更新

由于您不想使用任何外部插件,因此有一种可能的方法(有点棘手),那就是使用 jenkins-pipeline 中的以下脚本将开始时间保存在文件中:

def f = new File("/tmp/buildStart.txt")
def start = new Date().format('dd/MM/yyyy HH:mm:ss')
f.text = start
slackSend color: 'red', message: "Build start at ${start}"
Run Code Online (Sandbox Code Playgroud)

然后在构建完成的另一个 jenkins-pipeline 中,解析文件中的日期并获取与当前时间的差异:

def f = new File("/tmp/buildStart.txt")
def startDate = new Date().parse('dd/MM/yyyy HH:mm:ss',f.text)
def endDate = new Date()
def tookTime = groovy.time.TimeCategory.minus(endDate,startDate).toString()
slackSend color: 'red', message: "Total time: ${tookTime}"
Run Code Online (Sandbox Code Playgroud)

  • 我相信詹金斯可能提供了一种更优雅的方式,但我自己找不到。 (2认同)