如何显示在Jenkins中运行构建所花费的时间? [英] How to display the time it took to run a build in Jenkins?

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

问题描述

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

I'm configuring a process of Android application build by using Jenkins pipeline.

在构建的开始和结束时,都会将一条消息发送到相关的Slack频道.

At the beginning and the end of the build, a message is sent to a relevant Slack channel.

Jenkinsfile的相关部分如下所示:

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

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

In addition to the above information I'd like to also include the time it took for the build to run to that message which notifies about the end of the build.

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

Is that possible to do 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中的follow脚本将开始时间保存在文件中:

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管道中,从文件中解析日期并获得与当前时间的差值:

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天全站免登陆