Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping Jenkins job in case newer one is started

Is it possible to specify that, in case on job (A) is triggered more than once, that previous jobs are removed from queue, and only latest one is left in queue or started if there are enough free slots?

Thanks in advance!

like image 313
Dejan Menges Avatar asked Apr 23 '12 12:04

Dejan Menges


People also ask

How can I abort a running pipeline build if a new one is started?

Pipeline jobs can be stopped by sending an HTTP POST request to URL endpoints of a build. BUILD ID URL/stop - aborts a Pipeline. BUILD ID URL/term - forcibly terminates a build (should only be used if stop does not work).

How do you stop a stage in Jenkins pipeline?

Alternatively you can call error(String message) step to stop the pipeline and set its status to FAILED . For example, if your stage 1 calls error(msg) step like: stage("Stage 1") { steps { script { error "This pipeline stops here!" } } }

How do I abort all builds in Jenkins?

The builds in the pending queue can be easily cancelled from the Jenkins UI by manually clicking on the red "x" icon next to each build.


3 Answers

use execute system groovy script step:

import hudson.model.Result
import jenkins.model.CauseOfInterruption

//iterate through current project runs
build.getProject()._getRuns().each{id,run->
  def exec = run.getExecutor()
  //if the run is not a current build and it has executor (running) then stop it
  if( run!=build && exec!=null ){
    //prepare the cause of interruption
    def cause = new CauseOfInterruption(){ 
      public String getShortDescription(){
        return "interrupted by build #${build.getId()}"
      }
    }
    exec.interrupt(Result.ABORTED, cause)
  }
}

//just for test do something long...
Thread.sleep(10000)

and in the interrupted job there will be a log:

Build was aborted
interrupted by build #12
Finished: ABORTED 
like image 70
daggett Avatar answered Oct 26 '22 00:10

daggett


You can do it with a system Groovy Script run via Groovy Script Plugin. Such a script has direct access to Jenkins via its programming API. I do not see any other way.

like image 30
malenkiy_scot Avatar answered Oct 25 '22 23:10

malenkiy_scot


I don't think this problem can be solved perfectly by only adding a groovy script before build. If the new job come in while the older has already been building(it can't check the queue, since its pre-build part has passed), the new one still has to wait.

As I see, to achieve a preemptive job of jenkins, we need create another oversee job. This job should check that if there are new builds in the queue regularly and terminate older one if necessary.

But create a oversee job seems complex. I also expect a perfect solution.

like image 31
R.Liu Avatar answered Oct 25 '22 23:10

R.Liu