Determine if given job is currently running using Hudson/Jenkins API

好久不见. 提交于 2019-11-30 04:53:37

As gareth_bowles and Sagar said, using the Jenkins API is the way to know. If you put the depth to 1, you will see what you're looking for:

http://host/job/project/lastBuild/api/xml?depth=1

You will see there's a <building> tag to tell if that build is running

...
<build>
  <action>
    <cause>
        <shortDescription>Started by user Zageyiff</shortDescription>
        <userId>Zageyiff</userId>
        <userName>Zageyiff</userName>
    </cause>
  </action>
  <building>true</building>
  <duration>0</duration>
  <estimatedDuration>-1</estimatedDuration>
  <fullDisplayName>Project #12</fullDisplayName>
  <id>2012-08-24_08-58-45</id>
  <keepLog>false</keepLog>
  <number>12</number>
  <timestamp>123456789</timestamp>
  <url>
        http://host/job/project/12
  </url>
  <builtOn>master</builtOn>
  <changeSet/>
  <mavenVersionUsed>3.0.3</mavenVersionUsed>
</build>
...

If you go to your job's page, and add "api" to the end of the URL, you'll get information on using the API.

http://yourjenkins/job/job_name/api

More information on using the Jenkins API:

https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API

I'm using the Groovy plug-in, and run the following snippet as system:

import hudson.model.*
def version = build.buildVariableResolver.resolve("VERSION")
println "VERSION=$version"
def nextJobName = 'MY_NEXT_JOB'
def nextJob = Hudson.instance.getItem(nextJobName)
def running = nextJob.lastBuild.building
if (running) {
   println "${nextJobName} is already running. Not launching"
} else {
   println "${nextJobName} is not running. Launching..."
   def params = [
      new StringParameterValue('VERSION', version)
   ]
   nextJob.scheduleBuild2(0, new Cause.UpstreamCause(build), new ParametersAction(params))
}

It works like a charm.

If you're comfortable with digging through the Jenkins Java API, you could write a system Groovy script to get this data. The Job class is the place to start.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!