2

I have a Jenkins job in which at the end of the job (maybe around post actions or in the last stage of that job I want to find how much time has been elapsed since the job started.

How can find that? Is there any easy straightforward way of knowing it ?

Aayush
  • 133
  • 1
  • 3
  • 11

3 Answers3

1

Install Timestamper plugin.

The Timestamper plugin adds timestamps to the console output of Jenkins jobs. For example:

21:51:15  Started by user anonymous
21:51:15  Building on master
21:51:17  Finished: SUCCESS

/timestamps/ By default, display the elapsed time in seconds with three places after the decimal point.

/timestamps/?time=HH:mm:ss&appendLog Display the system clock time and append the line from the log.

/timestamps/?elapsed=HH:mm:ss.S&appendLog Display the elapsed time and append the line from the log.

/timestamps/?time=HH:mm:ss&elapsed=HH:mm:ss.S Display both the system clock time and the elapsed time.

/timestamps/?currentTime&time=HH:mm:ss Display the current time on the Jenkins controller.

Ian W
  • 4,559
  • 2
  • 18
  • 37
  • can you please provide example for declarative pipeline to show elapsed time? – Arunas Bartisius Jan 07 '22 at 13:38
  • @arunas-bartisius, It's [in the docs](https://www.jenkins.io/doc/pipeline/steps/timestamper/). – Ian W Jan 08 '22 at 01:49
  • it's not, as I mean declarative pipeline and NOT timestamps, but elapsed time. If you amend answer with declarative example +1 from me. agent any ... timestamps() shows timestamp, not elapsed time. – Arunas Bartisius Jan 08 '22 at 10:16
1

Sample pipeline script

pipeline {
    agent any

    stages {
        stage('Hello') {
            steps {
                echo 'Hello World'
                sleep 10
            }
        }
    }
    post {
        always {
            println "${currentBuild.durationString}"
        }
    }
}

Output:

[Pipeline] {
[Pipeline] stage
[Pipeline] { (Hello)
[Pipeline] echo
Hello World
[Pipeline] sleep
Sleeping for 10 sec
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] echo
14 sec and counting
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

if you don't like the and counting part you can always do

"${currentBuild.durationString}".replaceAll(' and counting', "")
Kaus2b
  • 747
  • 4
  • 12
1

Apart from all the answers above there is a very nice way of doing it:

import hudson.Util
.
.
.
String time = Util.getTimeSpanString(System.currentTimeMillis() - currentBuild.startTimeInMillis)

If you display time it will come in this format:

2 hr 15 min 47 sec

which is pretty neat and does not require any extra variable to be setup initially, also less editing needed (in my case I wanted in this exact way).

Aayush
  • 133
  • 1
  • 3
  • 11