您如何在 Jenkins 中获得构建持续时间? [英] How do you obtain build duration time in Jenkins?

查看:290
本文介绍了您如何在 Jenkins 中获得构建持续时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm configuring an Android application build process with Jenkins pipeline.

在构建开始和结束时,会向 Slack 频道发送一条消息.Jenkinsfile 的相关部分如下所示:

At the beginning and the end of the build, a message is sent to a Slack channel. The relevant portion of the Jenkinsfile looks like so:

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/ ")

我还希望 Slack 通知包含构建运行所需的时间.是否可以在不添加任何外部插件的情况下做到这一点?

I'd also like the Slack notification to include the time it took for the build to run. Is it possible to do this without adding any external plugins?

如果有一个环境变量可以保存这些信息,那就完美了,但我找不到这样的变量.

If there's an environment variable which holds this information it would be perfect, but I can't find such a variable.

推荐答案

由于这个 jenkins-pipeline 脚本在 Groovy 中,你可以简单地使用 new Date() 就可以了.message 参数上的 "Current time ${new Date()}" 之类的东西必须有效:

Since this jenkins-pipeline script is in Groovy you can simply use new Date() on it. Something like this "Current time ${new Date()}" on the message argument must work:

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

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

This will produce the follow message in your channel:

Current time: Thu Oct 13 17:25:12 CEST 2016

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

If you want a specific date format you can use format(String format) method, for example "${new Date().format('dd/MM/yyyy')}":

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

这将产生以下消息:

Current time: 13/10/2016

更新

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

Since you don't want to use any external plugins a possible way to do so (it's a little tricky) it's to save the start time in a file using the follow script in your 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}"

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

Then in an other jenkins-pipeline where your build finish, parse the date from the file and get the difference with the current time:

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}"

这篇关于您如何在 Jenkins 中获得构建持续时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆