jenkinsjenkins-pluginsjenkins-groovyjenkins-job-dsl

Find Jenkin jobs running more than 24 hours


I would like to find the Jenkin jobs in the master and client running more than 5 hours and kill it.

I tried multiple options using Thread.getAllStackTraces() and list all the jobs it was not helpful. Your help is much appreciated.


Solution

  • Searching in all the builds (past and present) can take a very long time. As an alternative, I suggest to search only the builds that are currently running, by looking at the activity on the nodes. This is much faster. This piece of pipeline script will list the jobs that have been running for more than 24 hours and send an email if it found one or more.

        int stuckJobs = 0
    
        def busyExecutors = Jenkins.instance.computers.collect { it.executors.findAll { it.isBusy() } }.flatten()
    
        busyExecutors.each {
            if (it.getElapsedTime() > 24 * 60 * 60 * 1000 ) {
                println("Job " + it.getCurrentWorkUnit().work.getDisplayName() + " has been running on " + it.getOwner().nodeName + " for " + it.getTimestampString())
                stuckJobs = stuckJobs + 1
            }
        }
        if (stuckJobs > 0) {
            emailext( from:    xxx,
                      subject: "[Jenkins] Stuck jobs report",
                      to:      yyy,
                      body:    "Found ${stuckJobs} job(s) lasting more than 24 hours. Check here: ${BUILD_URL}/console" )
        }